3 回答
![?](http://img1.sycdn.imooc.com/533e4c0500010c7602000200-100-100.jpg)
TA贡献1844条经验 获得超8个赞
我会检查一下this.state.restaurants
,componentDidUpdate
因为这是查看您的组件是否已更新的最佳方式。
这感觉就像你正在做正确的事情,如果你的第一个日志确实是正确的(似乎一种奇怪的方式来排序给我,我会打电话array.sort()
的newRestaurants
)。
也许在您的组件更新后的某个地方,某些东西将餐厅重新设置为原始值。
![?](http://img1.sycdn.imooc.com/533e4bd900011a1d02000200-100-100.jpg)
TA贡献1876条经验 获得超5个赞
newRestaurants = sort(newRestaurants, 'favourite');
这会改变原始数组并且不会创建新副本。
一种解决方法是使用 slice 函数创建一个新副本
newRestaurants = sort(newRestaurants, 'favourite').slice(); this.setState({ restaurants: newRestaurants });
![?](http://img1.sycdn.imooc.com/533e564d0001308602000200-100-100.jpg)
TA贡献1773条经验 获得超3个赞
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>
添加回答
举报