[英]Axios post method React. State Redux not update
I have problem with State
in Redux
This is my axios
request 我在
Redux
axios
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
Default state.error
, state.success
is empty array
. 默认
state.error
, state.success
为空array
。 After first click state.error
is still empty array because axois didn't finish request. 在第一次单击
state.error
之后仍然是空数组,因为axois没有完成请求。 After 2nd click everything is fine. 第二次点击后一切都很好。
And here i have problem with props: 这里我有道具问题:
{this.props.error.length>0? <div className="alert alert-danger">{this.props.error[0]}</div>: ''}
And store: 并存储:
@connect((store)=>{
return{
error: store.app.error,
success: store.app.success,
}
})
Do u know how i can render component
with new Props
after axios method post
finished. 在
axios method post
完成后,你知道我如何使用新的Props
渲染component
。
I think you have written this code into reducer, the api call should be done inside Action Dispacher . 我认为你已经将这段代码写入reducer,api调用应该在Action Dispacher中完成。 After api successfully called you have to dispatch data to reducer.
api成功调用后你必须将数据发送到reducer。 In reducer you should only assign the Data, no API Calls inside reducer.
在reducer中,您应该只在Reducer中分配Data,而不是API调用。
for eg 例如
Action Dispatcher 行动调度员
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))
});
}
}
Reducer 减速器
case 'API_DATA_RECD':
{
// you will get data from action.data
}
Axios is making an ajax request asynchronously, in the case REGISTER_USER , the piece of code it's returning the object with the state property right away meanwhile the request is still pending, that means the object has no meaninful values. Axios正在异步地发出ajax请求,在REGISTER_USER的情况下,它正在使用state属性立即返回对象的代码片段,同时请求仍处于未决状态,这意味着该对象没有任何有意义的值。 You should only return values whenever the request(s) you're making are completed.
只有在您完成的请求完成后,您才应返回值。
Try this: 尝试这个:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.