我正在尝试设置状态变量以响应来自api调用的数据,但无法这样做。我在responseJson中有除法数组,我正在尝试设置为状态除法数组。我在console.log上获得了responseJson值,但是当我尝试setState({... this.state,divisions:responseJson.division})时,我在控制台上没有任何数据。
状态
this.state={
token: data.token,
role: data.role,
userId: data.userId,
organizationId: data.organizationId,
organizationName: data.organization_name,
workspacePP: false,
workspaces: [],
divisions:[],
addWorkspace: null,
isDivisionViewable:false,
divisionName:null
};
功能addDivision
addDivision=()=> {
const uri = `${APPURL}/workspace/division/create`;
console.log('dddddd',this.state)
fetch(uri, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.state.token}`
},
body: JSON.stringify({
workspace_id: this.state.workspaces[0].workspace_id,
organization_id: this.state.organizationId,
division:this.state.divisionName
}),
}).then((res)=>res.json()).then(responseJson=>{
if(!responseJson.status){
message.error(responseJson.error);
return;
}
console.log('dddd',responseJson);
this.setState({...this.state,divisions:responseJson.division})
})
console.log(this.state)//returns empty array
}
响应Json
{status: true, division: Array(1), created_at: {…}, user: {…}}
created_at:
updated_at: ["2019-03-09 14:05:26"]
__proto__: Object
division: Array(1)
0: {id: 5, userid: "t863060h", workspace_id: "ROPHV6W", workspace_name:
"workspace", created_at: "2019-03-09 13:39:31", …}
length: 1
__proto__: Array(0)
status: true
user:
created_at: "2019-03-08 18:29:56"
email: "trycatchh@mail.com"
email_verification: 1
id: 1
loginStatus: 0
mobile_otp: 0
mobile_verification: 0
phone: "9632587410"
role: "Admin"
slug: ""
status: 2
team: null
uid: null
updated_at:“ 2019-03-08 18:29:56” 用户名:“ t863060h” 用户名:“ tryy catchh”
console.log(this.state)
nName: "tryCatchh", …}
addWorkspace: true
divisionName: "dud"
**divisions**: Array(0)//no data
length: 0
__proto__: Array(0)
isDivisionViewable: true
organizationId: "finalids"
organizationName: "tryCatchh"
role: "Admin"
userId: "t863060h"
workspacePP: false
workspaces: [{…}]
其他功能
showDivision=()=>{
console.log('dddd',this.state.divisions);
}
答案 0 :(得分:3)
SetState是异步的,因此要查看更新的状态值,您需要
更改
this.setState({...this.state,divisions:responseJson.division})
收件人
this.setState({
divisions:responseJson.division
}, () => {
console.log(this.state.divisions);//here you will get updated divisions state value
});
答案 1 :(得分:2)
请注意,您的setState位于 then 函数中,并将在API调用响应后运行。您的console.log(this.state)将在调用API后立即运行。
如果您想在API调用后看到最终状态,则将回调函数作为第二个参数传递给setState,如下所示:
this.setState({ divisions:responseJson.division }, () => console.log(this.state))
注意:调用setState时不需要破坏状态,React已经为您完成了。