Javascript 正在访问当前处理程序中的新状态
我有一个处理程序,它可以更改我的react应用程序的某些状态,比如说它洗牌状态条目Javascript 正在访问当前处理程序中的新状态,javascript,reactjs,Javascript,Reactjs,我有一个处理程序,它可以更改我的react应用程序的某些状态,比如说它洗牌状态条目数据: state = { data:[1,2,3,4,5] }; public handleShuffle = () => { const current = this.state.data; const shuffled = current .map((a: any) => [Math.random(), a]) .sort((a: any, b
数据
:
state = {
data:[1,2,3,4,5]
};
public handleShuffle = () => {
const current = this.state.data;
const shuffled = current
.map((a: any) => [Math.random(), a])
.sort((a: any, b: any): any => a[0] - b[0])
.map((a: any) => a[1]);
this.setState({
...this.state,
data: shuffled
});
consoleLog(this.state.data[0])
};
有没有办法访问此处理程序中仍然存在的新无序数组,以使日志不是1,而是新的无序状态?
setState
在将对象作为第一个参数传递时接受第二个回调参数:
this.setState({ data: shuffled }, () => {
this.state.data === shuffled // true
}
假设您在相同的作用域中,实际上不需要回调,因为您已经在shuffled
中拥有即将出现的状态的值,并且可以继续使用它
通常,如果要等到此.state
更新并且组件已重新呈现,建议使用componentdiddupdate
而不是setState
回调
请注意,
setState
将对传入的对象进行浅差分,并在新更新中合并。您不需要这样做:setState({…this.state})
,这样做实际上是有害的 setState
在将对象作为第一个参数传递时接受第二个回调参数:
this.setState({ data: shuffled }, () => {
this.state.data === shuffled // true
}
假设您在相同的作用域中,实际上不需要回调,因为您已经在shuffled
中拥有即将出现的状态的值,并且可以继续使用它
通常,如果要等到此.state
更新并且组件已重新呈现,建议使用componentdiddupdate
而不是setState
回调
请注意,
setState
将对传入的对象进行浅差分,并在新更新中合并。您不需要这样做:setState({…this.state})
,这样做实际上是有害的 您可以将第二个参数传递给setState
。
请试试这个:
this.setState({
...this.state,
data: shuffled
}, () => console.log(this.state.data[0]));
您可以将第二个参数传递给
setState
。
请试试这个:
this.setState({
...this.state,
data: shuffled
}, () => console.log(this.state.data[0]));
状态更新是异步的,
setState
具有回调
试试这个
public handleShuffle = () => {
const current = this.state.data;
const that = this;
const shuffled = current
.map((a: any) => [Math.random(), a])
.sort((a: any, b: any): any => a[0] - b[0])
.map((a: any) => a[1]);
this.setState({
...this.state,
data: shuffled
}, ()=>{
consoleLog(that.state.data[0])
});
};
状态更新是异步的,
setState
具有回调
试试这个
public handleShuffle = () => {
const current = this.state.data;
const that = this;
const shuffled = current
.map((a: any) => [Math.random(), a])
.sort((a: any, b: any): any => a[0] - b[0])
.map((a: any) => a[1]);
this.setState({
...this.state,
data: shuffled
}, ()=>{
consoleLog(that.state.data[0])
});
};