[英]React Parent Function Called from Child Component does not Update State?
I'm stuck on having my child component: ChildButton
call its parent component: ParentTable
's function that contains a "setState", to then refresh or update the table itself (in the parent).我坚持让我的子组件:
ChildButton
调用其父组件: ParentTable
包含“setState”的函数,然后刷新或更新表本身(在父级中)。
I am passing a getData
function from the parent to the child through props.我通过道具将
getData
函数从父级传递给子级。 On button click in the child - call a function to;在子项中单击按钮 - 调用函数; close a dialog, do a PUT on a mock api datastore, then call the
getData
function.关闭对话框,在模拟 api 数据存储上执行 PUT,然后调用
getData
函数。 The getData function does a GET from the api and does a setState on "apiData". getData 函数从 api 执行 GET 并在“apiData”上执行 setState。 Problem is the data is not updating in the parent table even though the getData function is being called.. Don't state changes cause a reload?
问题是即使调用 getData 函数,父表中的数据也没有更新。状态更改不会导致重新加载吗? Code below:
下面的代码:
ParentTable.jsx
export default function ParentTable() {
**const [apiData, setAPIData] = useState([]);**
const getData = () => {
axios.get(`https://blah.mockapi.io/fakeData`)
.then((getData) => {
**setAPIData**(getData.data);
})
console.log('getData'); // fires on child button click
}
return (
<Table..
<Table.Body>
{**apiData**.map((obj) => {
<Table.Cell>bunch of data from the obj..
<Table.Cell><ChildButton **getData={getData}**</Table.Cell>
... />../>../>
)
}
export default ParentTable;
ChildButton.jsx
const ChildButton = ({getData, ...}) => {
function handleClose() {
setOpen(false)
axios.put(`https://blah.mockapi.io/fakeData/${id}`, {
...
})
**getData()**
}
return (
<Button onClick={handleClose} ...>
Update
</Button>
)
}
export default ChildButton;
Long story short - why is my change of state in the Parent Component not updating it's table data?长话短说 - 为什么我在父组件中的状态更改没有更新它的表数据?
Axios.put returns a promise and you are not waiting for the response. Axios.put 返回一个承诺,您无需等待响应。 Invoke the getData function inside the .then function or use async await:
在 .then 函数中调用 getData 函数或使用 async await:
axios.put(`https://blah.mockapi.io/fakeData/${id}`, {
...
}).then(() => **getData()**)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.