gpt4 book ai didi

javascript - 调用上下文函数在 React 中不起作用

转载 作者:行者123 更新时间:2023-11-30 06:12:03 26 4
gpt4 key购买 nike

我正在尝试从子组件更新上下文的状态,但未调用上下文函数。

设置场景。这是在 Dashboard.jsx 中传递给 handleModal 的一些示例片段数据

{
_id: "123",
name: "test name",
details: test details,
content: "test content"
}


SnippetContext.js

handleSnippetUpdate函数应该从 Dashboard.jsx 中被调用不是。

  state = {
name: '',
details: '',
content: '',
}

handleSnippetUpdate = edit => event => {
console.log('invoked') //does not get invoked
this.setState({
name: edit.name,
details: edit.details,
content: edit.content,
})
}


仪表板.jsx

按钮调用 handleModal并传入片段数据。

<button type="button" onClick={() => this.handleModal(snippet)}>Edit</button>

  handleModal = snippet => {
console.log(snippet) //snippet data correctly arrives in the function

this.context.handleSnippetUpdate(snippet)
//DOES NOT WORK - need to know why and/or how to do correctly
//should pass snippet data to handleSnippetUpdate function



this.showModal.current.showModal()
//IGNORE - Runs a function in modal component which sets its state to true

}

最佳答案

handleSnippetUpdate 中删除 event => 已解决此问题。正如 HMR 和 trixn 在评论中指出的那样。

 handleSnippetUpdate = edit => event => {
console.log('invoked') //does not get invoked
this.setState({
name: edit.name,
details: edit.details,
content: edit.content,
})
}

关于javascript - 调用上下文函数在 React 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58324217/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com