我的问题是,在更新帖子标题时,我无法保留CurrentState,所以当我在更改帖子标题之前抛出一个错误来获取当前状态(即状态)时,我发现当前状态也更改为新状态,即使在更新之前我已经初始化了它!
我只想解释一下它是怎么工作的。
state = {
posts: [],
};
async componentDidMount() {
const { data: posts } = await axios.get(apiEndPoint);
this.setState({ posts });
}
handleUpdate = async (post) => {
let currentState;
currentState = this.state.posts;
console.log(currentState[0].title);
post.title = 'jsdhjs';
try {
await axios.put(apiEndPoint + '/' + post.id, post);
throw new Error('');
} catch (ex) {
alert('Something Failed While Updating The Post');
this.setState(currentState);
}
};
render(){
return(
<tbody>
{posts.map((post) => (
<tr key={post.id}>
<td>{post.title}</td>
<td>
<button
className='btn btn-info btn-sm'
onClick={() => this.handleUpdate(post)}
>
Update
</button>
</td>
</tr>
))}
</tbody>
)
}发布于 2020-07-21 11:50:50
您的状态更改的原因是对象的突变在javascript中如何工作。更多信息,参考资料。https://www.zeptobook.com/object-mutation-in-javascript/#:~:text=mutation%20in%20JavaScript.-,Object%20mutation%20in%20JavaScript,the%20reference%20to%20the%20value。
您可以将handleUpdate函数更新为
handleUpdate = async (post) => {
try {
await axios.put(apiEndPoint + '/' + post.id, {...this.state.posts[0], title: 'jsdhjs'});
throw new Error('');
} catch (ex) {
alert('Something Failed While Updating The Post');
}
};这样,您就不必考虑将其恢复到以前的组件状态,因为您从未改变过它。
https://stackoverflow.com/questions/63013510
复制相似问题