猿问

React setState 数组未排序

我的代码是这样的:


handleFavourite = id => {

    const { restaurants } = this.state;

    let newRestaurants = [...restaurants];

    newRestaurants = sort(newRestaurants, 'favourite');

    console.log(newRestaurants); // ALL GOOD

    this.setState({ restaurants: newRestaurants }, () => console.log(this.state.restaurants)); // CONSOLE LOG POSTS OLD DATA

};

所以在那里。回调函数setState显示旧数据,在 UI 中也没有任何东西被排序。为什么会这样?


编辑:发现问题。我也在使用static getDerivedStateFromProps,它每次都重置状态。


FFIVE
浏览 139回答 3
3回答

婷婷同学_

我会检查一下this.state.restaurants,componentDidUpdate因为这是查看您的组件是否已更新的最佳方式。这感觉就像你正在做正确的事情,如果你的第一个日志确实是正确的(似乎一种奇怪的方式来排序给我,我会打电话array.sort()的newRestaurants)。也许在您的组件更新后的某个地方,某些东西将餐厅重新设置为原始值。

慕运维8079593

 newRestaurants = sort(newRestaurants, 'favourite');这会改变原始数组并且不会创建新副本。一种解决方法是使用 slice 函数创建一个新副本newRestaurants = sort(newRestaurants, 'favourite').slice();  this.setState({ restaurants: newRestaurants });

慕容3067478

handleFavourite 似乎工作正常class App extends React.Component {&nbsp; state = {&nbsp; &nbsp; restaurants: ["a", "b", "c"]&nbsp; }&nbsp;&nbsp;&nbsp; handleFavourite = id => {&nbsp; &nbsp; const { restaurants } = this.state;&nbsp; &nbsp; let newRestaurants = [...restaurants];&nbsp; &nbsp; newRestaurants = sort(newRestaurants, 'favourite');&nbsp; &nbsp; console.log(newRestaurants); // ALL GOOD&nbsp; &nbsp; this.setState({ restaurants: newRestaurants }, () => console.log(this.state.restaurants)); // CONSOLE LOG POSTS OLD DATA}render() {&nbsp; const restaurants = this.state.restaurants.map(r => <p>{r}</p>)&nbsp; return (&nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; {restaurants}&nbsp; &nbsp; <hr/>&nbsp; &nbsp; <button onClick={this.handleFavourite}>sort</button>&nbsp; &nbsp; </div>&nbsp; )}}function sort(r) {&nbsp; return r.reverse();}ReactDOM.render(<App/>, document.getElementById("root"))<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script><div id="root"></div>
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答