[英]How to update react state immediately in functional component?
我在 react.useEffect 中有大量的逻辑,我想在 props.match 像这样改变时更新状态:
const [ start, setStart] = useState(0);
const [ end, setEnd] = useState(5);
React.useEffect(()=>{
if (!subcategory && !location && !search) {
setStart(0);
setEnd(5);
if (url.search) {
Axios.post(`http://localhost:5000/getAll${url.search}`)
.then((res) => {
setLen(res.data.length);
const sliced = res.data.slice(props.start, props.end);
props.fetchData(sliced);
setStart(end);
setEnd(prev=> prev + 5);
})
} else {
Axios.post('http://localhost:5000/getAll')
.then((res) => {
setLen(res.data.length);
const sliced = res.data.slice(props.start, props.end);
props.fetchData(sliced);
setStart(end);
setEnd(prev=> prev + 5);
})
}
return undefined;
}
},
[ props.match ]
);
为了让我的逻辑正常工作,我需要让开始和结束状态按顺序等于 0 和 5,并且它总是在 axios 获取它们之前更新它们。
我试过使用另一个 useEffect 但它没有用。 我也不想使用类组件。
如何在功能组件中立即更新状态?
我确实通过使用两个像这样的 useEffects 解决了这个大问题:
const [ start, setStart ] = useState(0);
const [ end, setEnd ] = useState(5);
const [ urlChanged, setUrlChanged ] = useState(false);
useEffect(
() => {
setStart(0);
setEnd(5);
setUrlChanged((prev) => !prev);
},
[ props.match ]
);
useEffect(
() => {
// logic using the latest end and start states
},
[ urlChanged ]
);
奇怪的是没有人像我那样在 stackoverflow 上回答过这个问题,因为每个人都说要使用类组件 this.setState({state : '' , callback function}) 。
要立即使用 useEffect,类似于类生命周期 componentDidMount 使用useEffect(()=>{},[])
在依赖项数组中没有任何内容。
否则,您需要传入您依赖的所有外部变量。 开始,结束,
您第一次使用 useState 似乎是多余的,因为您已经将它们设置为 0 和 5。每个 props.match 都会重新设置 useState
React.useEffect(()=>{
if (!subcategory && !location && !search) {
setStart(0); // redundant
setEnd(5); // redundant
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.