它們究竟意味着什麼?如果我理解正確it,計算新的狀態,當我不能使用this.state
,除非我通過一個函數作爲第一個參數setState()
:狀態更新可能是異步的
// Wrong
this.setState({a: f(this.state)});
// Correct
this.setState(prevState => {return {a: f(prevState)}});
但我可以用this.state
來決定做什麼:
if (this.state.a)
this.setState({b: 2});
道具怎麼樣?
// Correct or wrong?
this.setState({name: f(this.props)});
按理我不能指望this.state
調用this.setState
後改變:
this.setState({a: 1});
console.log(this.state.a); // not necessarily 1
然後,說我有一個用戶列表。以及選擇在那裏我可以做一個用戶當前:
export default class App extends React.Component {
...
setCurrentUserOption(option) {
this.setState({currentUserOption: option});
if (option)
ls('currentUserOption', option);
else
ls.remove('currentUserOption');
}
handleAddUser(user) {
const nUsers = this.state.users.length;
this.setState(prevState => {
return {users: prevState.users.concat(user)};
},() => {
// here we might expect any number of users
// but if first user was added, deleted and added again
// two callbacks will be called and setCurrentUserOption
// will eventually get passed a correct value
// make first user added current
if (! nUsers)
this.setCurrentUserOption(this.userToOption(user));
});
}
handleChangeUser(user) {
this.setState(prevState => {
return {users: prevState.users.map(u => u.id == user.id ? user : u)};
},() => {
// again, we might expect any state here
// but a sequence of callback will do the right thing
// in the end
// update value if current user was changed
if (_.get(this.state, 'currentUserOption.value') == user.id)
this.setCurrentUserOption(this.userToOption(user));
});
}
handleDeleteUser(id) {
this.setState(prevState => {
return {users: _.reject(prevState.users, {id})};
},() => {
// same here
// choose first user if current one was deleted
if (_.get(this.state, 'currentUserOption.value') == id)
this.setCurrentUserOption(this.userToOption(this.state.users[0]));
});
}
...
}
是否所有的回調批量更改狀態後順序執行的應用?
關於第二個想法,setCurrentUserOption
基本上就像setState
。它會將更改排入this.state
。即使回調被依次調用,我也不能依靠this.state
被以前的回調改變,我能嗎?所以它可能是最好不要提取setCurrentUserOption
方法:
handleAddUser(user) {
const nUsers = this.state.users.length;
this.setState(prevState => {
let state = {users: prevState.users.concat(user)};
if (! nUsers) {
state['currentUserOption'] = this.userToOption(user);
this.saveCurrentUserOption(state['currentUserOption']);
}
return state;
});
}
saveCurrentUserOption(option) {
if (option)
ls('currentUserOption', option);
else
ls.remove('currentUserOption');
}
這樣,我得到排隊的改變來currentUserOption
是免費的。
只需雙重檢查你是否使用了任何狀態管理框架,如redux或flux?答案可能會有所不同,具體取決於我要去的 – aug
。但現在我想讓它不用'redux'工作。 –