如何在reducer-react中存储注册用户数据


const initialUser = {
name: '',
email: '',
updated_at: '',
created_at: '',
id: ''
}

dispatch({type: 'user_register',payload: user })

正如你所看到的,我的草签和派遣。我希望我的用户存储在状态中。一切都很好。我无法将我的状态从initialState更改为user。

从您的reducer中,您应该始终返回一个新的Object

const reducer = (state, action) => {
switch(action.type){
case 'user_register':
console.log(action.payload, state)
return {
...state,
name:action.payload.name, 
email:action.payload.email
}

}
}
export function App(props) {
const initialUser = {
name: '',
email: '',
updated_at: '',
created_at: '',
id: ''
}
const [state, dispatch] = React.useReducer(reducer, initialUser)
React.useEffect(() => {
dispatch({type: 'user_register',payload: {name:"Testing", email:"testing@test.com"} }) // you can send your values which needs to be updated
},[])
React.useEffect(() => {
console.log(state)
},[state])
return (
<div className='App'>
</div>
);
}

我希望这个例子能解决您的疑问。

最新更新