首页 > 解决方案 > 从 axios 获取并使用 react-router 后,React 状态未在功能组件中更新

问题描述

所以我试图从子组件(子组件调用axios)更新父组件中的状态,然后我想通过路由将此状态从父组件发送到另一个子组件,但状态没有更新,可能是因为我是在路由中最初发送状态,谁能告诉我在 react-route 中发送更新状态的正确方法?

代码片段:

const ParentComponent = () =>{
const [info, setInfo] = useState([]);
...
...
...
      <Switch>
        <Route
          exact
          path="/child1Component"
          render={() => <Child1Component setData={setInfo} />}
        />
        <Route
          exact
          path="/child2Component"
          render={() => (
            <Child2Component dataApp={info} />
          )}
        />
      </Switch>
}

const Child1Component = (props) =>{
axios
    .get("URL", {
     
    })
    .then((response) => {
      props.setData(response.data);
      setLoading(false);
    });
    ...
    ...
    ...
}

我希望更新后的状态值作为 Child2Component 中的道具传递,现在它没有更新初始状态。

标签: axiosreact-routerhookreact-functional-componentreact-state

解决方案


推荐阅读