[英]React/Redux How to set value from redux store to state of component
I need to change my received data from redux store to another variable (and then modify it).我需要将收到的数据从 redux 存储更改为另一个变量(然后修改它)。 At the moment, I receive data from store after API call and it is stored offices
, but it is not set to my officeData
variable.目前,我在 API 调用后从 store 接收数据,它存储为officeData
offices
。 Does anyone how can I solve that?有谁可以解决这个问题?
This is my code:这是我的代码:
const dispatch = useDispatch();
const offices = useSelector((state) => state.office.offices)
const [officeData, setOffices] = useState(offices);
debugger;
useEffect(()=> {
dispatch(getOffices());
setOffices(offices);
debugger
}, [dispatch])
If you don't even enter your useEffect i think it's because you give dispatch
as a dependency.如果您甚至没有输入您的 useEffect 我认为这是因为您将dispatch
作为依赖项提供。
Effect are triggered when component mount but also when component update (prop or state).组件挂载时触发效果,组件更新(prop 或 state)时也会触发效果。 So you could do something like that:所以你可以做这样的事情:
import { useEffect } from "react";
const dispatch = useDispatch();
const offices = useSelector((state) => state.office.offices);
const [officeData, setOffices] = useState(undefined);
const [didMount, setDidmount] = useState(false);
// When component mount, load your Offices data
useEffect(() => {
if(!didMount){
dispatch(getOffices());
setOffices(offices);
} else {
setDidmount(true);
}
});
useEffect(() => {
if(didMount) {
// When you update officeData, do your thing
}
}, [officeData]);
I don't know the behavior of useSelector, but i guess it does not trigger a rendering.我不知道 useSelector 的行为,但我猜它不会触发渲染。 Maybe you could have a useEffect with offices as dependency , just be careful not to loop !也许你可以有一个 useEffect 与 office 作为依赖,只是要小心不要循环!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.