Axios post 方法反应。状态 Redux 不更新

Axios post method React. State Redux not update

我在 Redux 中遇到 State 的问题 这是我的 axios 请求

case 'REGISTER_USER':{

  var userData = {username: action.payload.username, password : action.payload.password};

  axios({
    method: 'post',
    url: 'php/register.php',
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    data: userData
  }).then(function(response) {
    state.error = response.data.errors;
    state.success = response.data.success;
});
    return {state};
    break;
  }//end REGISTER_USER

默认state.errorstate.success为空array。 第一次点击后 state.error 仍然是空数组,因为 axois 没有完成请求。第二次点击后一切正常。

这里我对道具有疑问:

{this.props.error.length>0? <div className="alert alert-danger">{this.props.error[0]}</div>: ''}

并存储:

@connect((store)=>{
  return{
    error: store.app.error,
    success: store.app.success,
  }
})

你知道我如何在 axios method post 完成后用新的 Props 渲染 component 吗?

Axios 正在异步发出 ajax 请求,在 REGISTER_USER 的情况下,这段代码是 return 立即使用状态 属性 对象该请求仍未决,这意味着该对象没有有意义的值。每当您提出的请求完成时,您应该只 return 值。

试试这个:

case 'REGISTER_USER':{

  var userData = {username: action.payload.username, password : action.payload.password};

  axios({
    method: 'post',
    url: 'php/register.php',
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    data: userData
  }).then(function(response) {
    state.error = response.data.errors;
    state.success = response.data.success;

    return {state}
});
    break;
  }//end REGISTER_USER

我认为你已经将这段代码写入了 reducer,api 调用应该在 Action Dispacher 中完成。在 api 成功调用后,您必须将数据分派给 reducer。在 reducer 中你应该只分配数据,没有 API reducer 内部的调用。

例如

动作调度程序

export function APIDispatch(data)
{
    return{
        type:'API_DATA_RECD',                
        data:data
    }
}

export function callAPI(){
    return function(dispatch){
         axios({
            method: 'post',
            url: 'php/register.php',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: userData
          }).then(function(response) {
            state.error = response.data.errors;
            state.success = response.data.success;
            dispatch(APIDispatch(state))
        });

    }
}

减速器

case 'API_DATA_RECD':
    {   
        // you will get data from action.data
    }