预期效果:点击<li>--> 获取索引 --> 将此索引发送到组件Watch。当我单击 时<li>,我抓取索引并将其移动到Watch组件。但是,当我单击第二个时,li它会返回我第一次单击的索引。我认为这是因为它通过componentDidMount. 之后如何引用此索引componentDidMount?去做class Todo extends Component { render () { return ( <div className = "itemTodos" onClick={()=> this.props.selectTodo(this.props.index)}> </div> ) } } export default Todo;应用程序class App extends Component { constructor(){ super(); this.state { selectedTodoIndex: index } } selectTodo = (index) => { this.setState({ selectedTodoIndex: index }) } render () { return ( <div> <ul> { this.state.todos .map((todo, index) => <Todo key={index} index={index} todo={todo} selectTodo ={this.selectTodo} /> ) } </ul> <Watch selectedTodoIndex = {selectedTodoIndex} /> </div> ) } }export default App;手表class Watch extends Component { constructor(){ super(); this.state = { selectIndex: null } } componentDidMount() { this.setState({ selectIndex: this.props.selectedTodo }); } render () { return ( <div> </div> ) } }
3 回答

小怪兽爱吃肉
TA贡献1852条经验 获得超1个赞
如果我没有错,你的 Todo 组件正在监视中??。所以Watch组件应该是这样的:
render () {
return (
<div>
<Todo index={this.state.selectedIndex} selectedTodo={this.props.selectedTodoIndex}/>
</div>
)
}
在这里,我制作了这段代码的代码和盒子。请随时结帐,如果您有任何疑问,请告诉我。代码链接:https : //codesandbox.io/s/frosty-chaplygin-ws1zz

慕桂英4014372
TA贡献1871条经验 获得超13个赞
有很多改进要做。但我相信您正在寻找的是Watch Component 中的getDerivedStateFromProps lifeCycle 方法。所以代码将是:
getDerivedStateFromProps(nextProps, prevState) {
if(nextProps.selectedTodoIndex !== prevState.selectedTodoIndex) {
return { selectIndex: nextProps.selectedTodoIndex }
}
}
这将检查 App 组件中选定的索引是否已更改,如果是,它将更新 Watch 组件中的状态。
添加回答
举报
0/150
提交
取消