如何将我的 Redux 初始状态设置为对象,然后将其与我的 reducer 函数正确同步?
How can I setup my Redux Initial state as an Object, and then properly sync it with my reducer functions?
所以我是 React Redux 的新手,我能够设置一个减速器,从后端获取一个数字,并允许我将它递增或递减 1000。
在服务器端,数字来自 'routes/api/users' 文件并显示
const express = require('express')
var cors = require('cors');
const { Router } = require('express');
const router = express.Router();
const number = {count:2150, holder:'James'}
router.get('/', async(req,res)=>{
console.log('a GET request was made', req.body)
res.send(number)
})
router.post('/', async(req,res)=>{
console.log('a POST request was made', req.body)
number.count = req.body.count
res.send(number)
})
module.exports = router;
所以后端发送number,这是一个对象,有holder name和count。==> {count:2150, holder:James}
React 前端然后通过这个 reducer 函数获取计数
/// FETCH DATA
export const GetData = () =>{
return async (dispatch, getState) =>{
const response = await axios.get('http://localhost:9700/api/users')
console.log('it worked ', response.data.count)
dispatch({
type:"FETCH_DATA",
payload: response.data.count})
}}
这是reducer代码
const reducer = (state = number, action )=>{
switch(action.type){
case "FETCH_DATA":
return action.payload
case "deposit":
return state + action.payload;
case "withdraw":
return state - action.payload;
case "POST_DATA":
state = action.payload
return action.payload;
default:
return state;
}}
这是剩下的代码
import axios from "axios"
//// ADD MONEY TO ACCOUNT
export const depositMoney = (amount) =>{
return (dispatch) =>{
dispatch ({
type:"deposit",
payload:amount})
}}
//// WITH DRAW MONEY FROM ACCOUNT
export const withDrawMoney=(amount)=>{
return (dispatch)=>{
dispatch({
type:"withdraw",
payload:amount })
}}
/// FETCH DATA
export const GetData = () =>{
return async (dispatch, getState) =>{
const response = await axios.get('http://localhost:9700/api/users')
console.log('it worked ', response.data.count)
dispatch({
type:"FETCH_DATA",
payload: response.data.count})
}}
// POST DATA
export const PostData = (num) =>{
return async (dispatch, getState) =>{
const newUser ={
id:num,
name:"Heynow"
}
const config = {
headers:{
'Content-Type':'application/json'
} }
const body = JSON.stringify(newUser)
const response= await axios.post('http://localhost:9700/api/users', body, config)
console.log('it worked ', response.data.count)
dispatch({
type:"POST_DATA",
payload: response.data.count })
}};
这是App.js代码
import {useSelector} from "react-redux"
import { bindActionCreators } from 'redux';
import { actionCreators } from './State/index';
import { useDispatch } from 'react-redux';
import { useEffect } from 'react';
import { useState } from 'react';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom'
import './App.css';
import { PostData, Dummy, GetData } from './State/actions-creators';
function App() {
const account = useSelector((state)=>state.account);
const dispatch = useDispatch();
console.log(account)
const {depositMoney, withDrawMoney} = bindActionCreators(actionCreators,dispatch)
useEffect(()=>{
dispatch(GetData());
console.log('hey')
},[]);
return (
<div className="App">
<h3>{account}</h3>
<button onClick={()=>depositMoney(1000)}>Add</button>
<button onClick={()=>withDrawMoney(1000)}>Subtract</button>
<button onClick={()=>PostData(0)}>Reset</button>
</div>
);
}
export default App;
所以我有两个问题
1-首先是我的 post 函数不起作用,PostData 函数假设将计数重置为 0 并将其发送到服务器并从服务器获取显示其为 0 的更新
但是,当我单击重置按钮(链接到 PostData 函数)时没有任何反应
2- 我试过将状态从数字更改为具有持有人姓名和计数的对象,就像它在背面的情况一样。但是我不断收到错误消息
Error: Objects are not valid as a React child (found: object with keys {count, holder}). If you meant to render a collection of children, use an array instead.
有人可以告诉我如何将 initialState 设置为对象而不导致整体功能出错吗?
这是我尝试过的错误
const reducer = (state = {name:'',count:''}, action )=>{
switch(action.type){
case "FETCH_DATA":
return action.payload
case "deposit":
return {...state, count:state.count + action.payload};
case "withdraw":
return {...state, count:state.count - action.payload};
case "POST_DATA":
return action.payload;
default:
return state;
}}
export default reducer
这是修改后的函数文件
import axios from "axios"
//// ADD MONEY TO ACCOUNT
export const depositMoney = (amount) =>{
return (dispatch) =>{
dispatch ({
type:"deposit",
payload:amount})
}}
//// WITH DRAW MONEY FROM ACCOUNT
export const withDrawMoney=(amount)=>{
return (dispatch)=>{
dispatch({
type:"withdraw",
payload:amount })
}}
/// FETCH DATA
export const GetData = () =>{
return async (dispatch, getState) =>{
const response = await axios.get('http://localhost:9700/api/users')
console.log('it worked ', response.data.count)
dispatch({
type:"FETCH_DATA",
payload: response.data})
}}
// POST DATA
export const PostData = (num) =>{
return async (dispatch, getState) =>{
const newUser ={
id:num,
name:"Heynow"
}
const config = {
headers:{
'Content-Type':'application/json'
} }
const body = JSON.stringify(newUser)
const response= await axios.post('http://localhost:9700/api/users', body, config)
console.log('it worked ', response.data.count)
dispatch({
type:"POST_DATA",
payload: response.data })
}};
那么我需要做些什么才能正确地将 reducer 与 {count:'',holder:''} 的初始状态同步?
如果有人能提供帮助,我们将不胜感激。
谢谢。
首先,您通过 POST 发送的正文与服务器预期的请求不匹配(holder
和 count
与 name
和 id
属性).
其次,您收到的错误表明您尝试渲染(return 在功能组件的情况下)一个 javascript 对象,这是被禁止的。您可以做的是销毁错误对象或只是 return 它的属性之一,例如
不好
const data = { count: 1, holder: 'John' };
return (
<h1>{data}</h1>
);
好
const data = { count: 1, holder: 'John' };
return (
<>
<span>{data.count}</span>
<span>{data.holder}</span>
</>
);
所以我是 React Redux 的新手,我能够设置一个减速器,从后端获取一个数字,并允许我将它递增或递减 1000。
在服务器端,数字来自 'routes/api/users' 文件并显示
const express = require('express')
var cors = require('cors');
const { Router } = require('express');
const router = express.Router();
const number = {count:2150, holder:'James'}
router.get('/', async(req,res)=>{
console.log('a GET request was made', req.body)
res.send(number)
})
router.post('/', async(req,res)=>{
console.log('a POST request was made', req.body)
number.count = req.body.count
res.send(number)
})
module.exports = router;
所以后端发送number,这是一个对象,有holder name和count。==> {count:2150, holder:James}
React 前端然后通过这个 reducer 函数获取计数
/// FETCH DATA
export const GetData = () =>{
return async (dispatch, getState) =>{
const response = await axios.get('http://localhost:9700/api/users')
console.log('it worked ', response.data.count)
dispatch({
type:"FETCH_DATA",
payload: response.data.count})
}}
这是reducer代码
const reducer = (state = number, action )=>{
switch(action.type){
case "FETCH_DATA":
return action.payload
case "deposit":
return state + action.payload;
case "withdraw":
return state - action.payload;
case "POST_DATA":
state = action.payload
return action.payload;
default:
return state;
}}
这是剩下的代码
import axios from "axios"
//// ADD MONEY TO ACCOUNT
export const depositMoney = (amount) =>{
return (dispatch) =>{
dispatch ({
type:"deposit",
payload:amount})
}}
//// WITH DRAW MONEY FROM ACCOUNT
export const withDrawMoney=(amount)=>{
return (dispatch)=>{
dispatch({
type:"withdraw",
payload:amount })
}}
/// FETCH DATA
export const GetData = () =>{
return async (dispatch, getState) =>{
const response = await axios.get('http://localhost:9700/api/users')
console.log('it worked ', response.data.count)
dispatch({
type:"FETCH_DATA",
payload: response.data.count})
}}
// POST DATA
export const PostData = (num) =>{
return async (dispatch, getState) =>{
const newUser ={
id:num,
name:"Heynow"
}
const config = {
headers:{
'Content-Type':'application/json'
} }
const body = JSON.stringify(newUser)
const response= await axios.post('http://localhost:9700/api/users', body, config)
console.log('it worked ', response.data.count)
dispatch({
type:"POST_DATA",
payload: response.data.count })
}};
这是App.js代码
import {useSelector} from "react-redux"
import { bindActionCreators } from 'redux';
import { actionCreators } from './State/index';
import { useDispatch } from 'react-redux';
import { useEffect } from 'react';
import { useState } from 'react';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom'
import './App.css';
import { PostData, Dummy, GetData } from './State/actions-creators';
function App() {
const account = useSelector((state)=>state.account);
const dispatch = useDispatch();
console.log(account)
const {depositMoney, withDrawMoney} = bindActionCreators(actionCreators,dispatch)
useEffect(()=>{
dispatch(GetData());
console.log('hey')
},[]);
return (
<div className="App">
<h3>{account}</h3>
<button onClick={()=>depositMoney(1000)}>Add</button>
<button onClick={()=>withDrawMoney(1000)}>Subtract</button>
<button onClick={()=>PostData(0)}>Reset</button>
</div>
);
}
export default App;
所以我有两个问题
1-首先是我的 post 函数不起作用,PostData 函数假设将计数重置为 0 并将其发送到服务器并从服务器获取显示其为 0 的更新 但是,当我单击重置按钮(链接到 PostData 函数)时没有任何反应
2- 我试过将状态从数字更改为具有持有人姓名和计数的对象,就像它在背面的情况一样。但是我不断收到错误消息
Error: Objects are not valid as a React child (found: object with keys {count, holder}). If you meant to render a collection of children, use an array instead.
有人可以告诉我如何将 initialState 设置为对象而不导致整体功能出错吗?
这是我尝试过的错误
const reducer = (state = {name:'',count:''}, action )=>{
switch(action.type){
case "FETCH_DATA":
return action.payload
case "deposit":
return {...state, count:state.count + action.payload};
case "withdraw":
return {...state, count:state.count - action.payload};
case "POST_DATA":
return action.payload;
default:
return state;
}}
export default reducer
这是修改后的函数文件
import axios from "axios"
//// ADD MONEY TO ACCOUNT
export const depositMoney = (amount) =>{
return (dispatch) =>{
dispatch ({
type:"deposit",
payload:amount})
}}
//// WITH DRAW MONEY FROM ACCOUNT
export const withDrawMoney=(amount)=>{
return (dispatch)=>{
dispatch({
type:"withdraw",
payload:amount })
}}
/// FETCH DATA
export const GetData = () =>{
return async (dispatch, getState) =>{
const response = await axios.get('http://localhost:9700/api/users')
console.log('it worked ', response.data.count)
dispatch({
type:"FETCH_DATA",
payload: response.data})
}}
// POST DATA
export const PostData = (num) =>{
return async (dispatch, getState) =>{
const newUser ={
id:num,
name:"Heynow"
}
const config = {
headers:{
'Content-Type':'application/json'
} }
const body = JSON.stringify(newUser)
const response= await axios.post('http://localhost:9700/api/users', body, config)
console.log('it worked ', response.data.count)
dispatch({
type:"POST_DATA",
payload: response.data })
}};
那么我需要做些什么才能正确地将 reducer 与 {count:'',holder:''} 的初始状态同步?
如果有人能提供帮助,我们将不胜感激。
谢谢。
首先,您通过 POST 发送的正文与服务器预期的请求不匹配(holder
和 count
与 name
和 id
属性).
其次,您收到的错误表明您尝试渲染(return 在功能组件的情况下)一个 javascript 对象,这是被禁止的。您可以做的是销毁错误对象或只是 return 它的属性之一,例如
不好
const data = { count: 1, holder: 'John' };
return (
<h1>{data}</h1>
);
好
const data = { count: 1, holder: 'John' };
return (
<>
<span>{data.count}</span>
<span>{data.holder}</span>
</>
);