如何解决如何在功能组件中立即更新反应状态?
react.useEffect中包含大量逻辑,并且每当prop.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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。