我有一个父组件,它呈现从 API 中提取的子列表(其功能正确)。每个孩子都可以选择删除自己。当孩子删除自己时,我无法让父母重新渲染。我在这里阅读了与该主题相关的大约 50 个答案,并尝试了所有这些答案,但似乎没有任何效果。我错过了一些东西并卡住了。
该组件已连接了 redux,但我已经尝试了连接和不连接 redux 的代码。我还在回调中尝试了 this.forceUpdate() ,它也不起作用(我在下面的示例代码中将其注释掉了)。
class Parent extends React.Component {
constructor(props) {
super(props)
this.refresh = this.refresh.bind(this)
this.state = {
refresh: false,
}
}
componentDidMount(){
this.getChildren()
}
refresh = () => {
console.log("State: ", this.state)
this.setState({ refresh: !this.state.refresh })
// this.forceUpdate();
console.log("new state: ", this.state)
}
getChildren = () => {
axios.get(
config.api_url + `/api/children?page=${this.state.page}`,
{headers: {token: ls('token')}
}).then(resp => {
this.setState({
children: this.state.children.concat(resp.data.children)
)}
})
}
render(){
return (
<div>
{_.map(this.state.children, (chidlren,i) =>
<Children
key={i}
children={children}
refresh={() => this.refresh()}
/>
)}
</div>
)
}
}
然后在我的 Children 组件中,它工作得很好,并且删除按钮成功地从数据库中删除了记录,我有以下摘录:
deleteChild = (e) => {
e.preventDefault();
axios.delete(
config.api_url + `/api/children/${this.state.child.id}`,
{headers: {token: ls('token')}}
).then(resp => {
console.log("The response is: ", resp);
})
this.props.refresh();
}
render() {
return(
<button class="btn" onClick={this.deleteChild}>Delete</button>
)}
}
我确定我缺少一些简单或基本的东西,但我找不到它。