反应 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,它每次都会重置状态。

我会在componentDidUpdate中检查this.state.restaurants,因为这是查看组件是否已更新的最佳方法。

如果你的第一个日志确实是正确的,感觉就像你在做正确的事情(这对我来说似乎是一种奇怪的排序方式,我会在newRestaurants上打电话给array.sort()(。

也许在您的组件更新后的某个地方,某些东西正在使餐厅再次恢复到其原始值。

handleFavourite似乎还可以。

class App extends React.Component {
state = {
restaurants: ["a", "b", "c"]
}

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
}
render() {
const restaurants = this.state.restaurants.map(r => <p>{r}</p>)
return (
<div>
{restaurants}
<hr/>
<button onClick={this.handleFavourite}>sort</button>
</div>
)
}
}
function sort(r) {
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>

newRestaurants = sort(newRestaurants, 'favourite'); 
// This mutates the original array and does not create a new copy.
A workaround is to create a new copy using slice function
newRestaurants = sort(newRestaurants, 'favourite').slice(); 
this.setState({ restaurants: newRestaurants });

最新更新