3 回答

TA貢獻(xiàn)1779條經(jīng)驗(yàn) 獲得超6個(gè)贊
“使用檢查員,盧克!” ~ 歐比旺 Reactnobi
在您的setState通話中,您正在合并狀態(tài)本身的內(nèi)容newUser以及first_name狀態(tài)本身,而不是狀態(tài)的newUser字段。因此,在更新狀態(tài)后,您最終會得到以下數(shù)據(jù):
{
newUser: { /* the initial value*/ },
// all the other proprerties inside `newUser`, such as
email: "",
age: 0,
// then the key you merged into the state explicitly:
first_name: "whatever the user typed"
}
你可能打算這樣寫(記住這setState已經(jīng)是一個(gè)淺合并,所以只有newUser在你的狀態(tài)對象中有更多值時(shí)才會更新):
this.setState({
newUser: {
...this.state.newUser,
first_name: text
}
})

TA貢獻(xiàn)1793條經(jīng)驗(yàn) 獲得超6個(gè)贊
你能試試這個(gè)
onChangeText={(text) => this.setState({
newUser : {
...this.state.newUser,
first_name: text,
}
}), () => {console.log(this.state.newUser.first_name)}

TA貢獻(xiàn)1810條經(jīng)驗(yàn) 獲得超5個(gè)贊
首先,您必須僅使用根對象更新狀態(tài)
你不能像那樣更新狀態(tài)
onChangeText={(text) => this.setState({
...this.state.newUser,
first_name: text
}), () => {console.log(this.state.newUser.first_name)}}
讓我給你我的自定義函數(shù)。
updateObject = (oldObject, updatedProperties) => {
return {
...oldObject,
...updatedProperties
};};
你可以這樣使用
onChangeText={(text) => {
let updatedFormElement ;
updatedFormElement = this.updateObject(this.state.newUser, {
first_name: text
});
this.setState({ newUser: updatedFormElement });
}}
添加回答
舉報(bào)