如何在axios()。then()中使用useContext钩子的调度函数?

时间:2020-02-04 17:28:39

标签: javascript reactjs react-hooks

在我的组件中

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”未更新

2 个答案:

答案 0 :(得分:0)

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);

答案 1 :(得分:-1)

如果您可以发布整个组件,这将有所帮助,但是我还是要坚持一下...

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

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

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

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