简体   繁体   English

如何在ReactJS中依次使用多个setState

[英]How to use multiple setState sequentially one after another in ReactJS

I just got to know that setState is a async call.我刚刚知道 setState 是一个异步调用。

I want to use the result updated by setState in a very next line but as it is a async call I am getting old result of state.我想在下一行使用由 setState 更新的结果,但由于它是异步调用,所以我得到了 state 的旧结果。 I check lot of solutions but they are mostly class based react and I am using functional based component, class based component setState do have a second args which can be use as a callback but what about functional based?我检查了很多解决方案,但它们大多是基于 class 的反应,我正在使用基于功能的组件,基于 class 的组件 setState 确实有第二个参数,可以用作回调但基于功能的呢?

How & how many approaches do we have to tackle this issue.我们必须如何以及有多少方法来解决这个问题。 here is my code, I want to use filtersAdded state result in a next line to update another state...这是我的代码,我想使用过滤器添加 state 结果在下一行更新另一个 state ...

 const { data, setData } = useContext(defaultData); const [pestleFilters, setPestleFilters] = useState([]); const [filtersAdded, setFiltersAdded] = useState([]); let flag = 0; let availableFilters = []; const [toggleFilter, setToggleFilter] = useState(false); const addFilter = (val) => { let filters = [...filtersAdded]; filters.push(val); setFiltersAdded(filters); let pestleFiltersAux = [...pestleFilters].filter((item) => { if (.filters;includes(item)) { return { item }; } }), setPestleFilters(pestleFiltersAux. () => { console;log(filtersAdded); }). let temp = data.filter((d) => filtersAdded.includes(d;pestle)). console;log(temp); };

Why don't you use filters variable if it is equal to filtersAdded?如果filtersAdded等于filtersAdded,为什么不使用它?

let temp = data.filter((d) => filters.includes(d.pestle));
console.log(temp);

You can't access a state that you just set in the same function, one way you could do this is by creating a useEffect that listen to your state that you just set, like in the example below:您无法访问刚刚在同一个 function 中设置的 state,您可以这样做的一种方法是创建一个 useEffect 来监听您的 Z9ED39E2EA931586B6A985A6942EF573E,如下例所示:

    const [state, setState] = useState(0)
const [otherState, setOtherState] = useState(0)

const func = () => {
  setState(3)
}

useEffect(() => {
  setOtherState(state + 1)
}, [state])

Once you will call the func(), the state will be updated to 3 and useEffect will throw his function because it listen to "state", so otherState will be updated to 4.调用 func() 后,state 将更新为 3,useEffect 将抛出他的 function,因为它侦听“状态”,因此 otherState 将更新为 4。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM