【问题标题】:Code not working after redux function in axios call在axios调用中的redux函数后代码不起作用
【发布时间】:2021-01-23 12:57:52
【问题描述】:

我在使用 redux/axios 时遇到问题。我想在一个axios请求成功后改变store,在store改变之后我想改变应用状态。我希望代码能够到达我的功能,但这并没有发生,我不知道为什么! redux 是异步的吗?如果是这样,我该如何进行同步呼叫? (下面留下一些代码)

        axios.post(url,{
            "system":system,
        })
        .then(res => {
          this.props.setTest(res) #code does not follow this line, no state is set
          this.setState({
            test_data:res,
            redirect:true
          })
        })
        .catch((error)=>{
          if(error.response){
              if(error.response.data["Error"]){
                  console.log("There was an error fetching the test")
              }
          }
      })
export function setTest(test){
    return {type: "SET_TEST",payload: test}
}
case "SET_TEST":{
            console.log("SET_TEST")
            return {
                ...state,

                (and other changed args)
            };
}

感谢您的帮助!

【问题讨论】:

    标签: reactjs redux axios


    【解决方案1】:

    this.props.setTest(res) 很可能会触发某种错误。

    因为后来你有一个catch 块,你只处理非常具体的错误,这个错误永远不会出现,你永远不会知道错误是什么,直到你控制台记录它。 所以:

    .catch((error)=>{
        if(error.response && error.response.data["Error"]){
           console.log("There was an error fetching the test")
        } else {
           // don't swallow your error, log it!
           console.log("some unexpected error happened:", error);
        }
    
    

    【讨论】:

    • 谢谢!确实是错误,但由于没有打印我不知道
    【解决方案2】:

    我认为您不了解 Redux 的工作原理。在您的情况下, setTest 返回一个动作。需要分派操作。

    试试这个:

    import { useDispatch } from "react-redux"; 
    

    // 在你的组件中

    const dispatch = useDispatch();
    dispatch(setTest(res));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-26
      • 1970-01-01
      • 2020-06-23
      • 2017-06-22
      • 2018-06-29
      • 2021-06-11
      相关资源
      最近更新 更多