【问题标题】:how to use dispatch function of useContext hook inside a axios().then()?如何在 axios().then() 中使用 useContext 钩子的调度函数?
【发布时间】:2020-02-04 17:28:39
【问题描述】:

在我的组件中

axios({
    method: 'get',
    url: `${SERVER_URL}crawler/get-customer/${uniqueId}`,
}).then(function (response) {
    if(response.data){
        console.log("response",response);
        responseData = response.data;
     dispatch({ type: 'SET_IMG', payload: { url: responseData.logo_url } });
    }
},[]);

应有的响应,但调度是递归的,几乎让我的浏览器崩溃,并且数据“url”没有更新

【问题讨论】:

  • 你是如何以及在哪里通过 axios 执行你的 api 请求的
  • 使用django本地服务器,api请求没有问题,我用useEffect()钩子解决了这个问题。感谢您的宝贵时间。

标签: javascript reactjs react-hooks


【解决方案1】:
useEffect(() => {
    axios({
        method: 'get',
        url: `${SERVER_URL}crawler/get-customer/${uniqueId}`,
    }).then(function (response) {
        if(response.data){
           console.log("response",response);
           responseData = response.data;
           props.functionName(response.data);
      }
},[]);

const mapDispatchToProps = dispatch => {
return {
functionName: (data) => dispatch({
        type:'SET_IMG',
        payload: { url: responseData.logo_url }
    })
 }
}

export default connect(, mapDispatchToProps)(nameComponent);

【讨论】:

    【解决方案2】:

    如果你能发布你的整个组件会有所帮助,但无论如何我都会采取行动......

    我假设您的组件也将获取的数据值从状态中取出(redux?),然后很可能会发生这种类型的循环:

    • 组件渲染
    • 获取数据
    • 更新状态值(redux?)
    • 组件呈现,因为值已更新
    • 获取数据
    • 更新状态值

    您是否打算只获取一次数据?如果你这样做:

    useEffect(() => {
      axios({...}).then(...);
    }, []);
    

    【讨论】:

    • 不要刺伤,要求澄清,然后在我们了解所有细节后回答。
    • 这真的是规则吗?我觉得我清楚地列出了我的假设,这仍然会带来有益的反应。
    • 我使用了 useEffect,它正在工作,谢谢,我没有使用 REDUX。 ,只需反应钩子
    猜你喜欢
    • 2021-12-03
    • 2019-06-30
    • 1970-01-01
    • 1970-01-01
    • 2021-08-08
    • 2020-06-02
    • 2022-01-21
    • 1970-01-01
    • 2022-01-24
    相关资源
    最近更新 更多