微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

React:当子组件表单提交时重新获取父组件中的数据

如何解决React:当子组件表单提交时重新获取父组件中的数据

我有一个获取项目列表的父组件,这些通过子组件传递,最终到达每个项目的单独表单,您可以在其中更新它。表单提交后,items 的值会明显改变,但父组件不会重新渲染。

我明白为什么会发生这种情况,但是我坚持使用解决方案来解决这个问题。每当提交其中一个表单时,如何让父组件重新获取数据?我可以改为更新父状态,但它不是直系子节点(类似于曾孙……)。将所有这些获取的数据保存到 Redux 并在那里更新会更容易吗?不确定这里有哪些最佳做法!

父组件(简化):

const ThisMonth = () => {
const [expenses,setExpenses] = useState()

useEffect(() => {
    axiosGet('this-month-expenses/').then(res => setExpenses(res.data))
},[])

return (<ExpenseList expenses={expenses} />)

}

费用道具会向下传递一些组件,直到它到达表单(也已简化):

const ExpenseForm = ({ expense }) => {
const color = useSelector(state => {return state.user.color})
const [name,setName] = useState(expense.name)
const [category,setCategory] = useState(expense.icon.name)
const [date,setDate] = useState(Date.parse(expense.date))
const [cost,setCost] = useState(expense.cost)
const [submitting,setSubmitting] = useState(false)

const submitForm = () => {
    setSubmitting(true)
    axiosPost('expense/',{
        "id": expense.id,"name": name,"date": date,"cost": cost,"category": category
    })
    .then((res) => (setSubmitting(!(res.status === 200))))
}

return (
        <form>Form here...</form>
        <Button 
            onClick={() => submitForm()}
            isLoading={submitting}
            w='100%' 
            colorScheme={color} 
            color='white' 
            mt={5}
            type="submit"
        >Update Expense</Button>
)

}

解决方法

您可以在父 fetchData().. 中有一个函数,然后将其作为道具提供给子项。在提交时调用它,作为 callback

有关更多详细信息,请添加一个最小的工作示例。

编辑; 做这样的事情

const ExpenseForm = ({ expense,onSubmitCallback }) => {
...

const submitForm = () => {
    setSubmitting(true)
    axiosPost('expense/',{
        "id": expense.id,"name": name,"date": date,"cost": cost,"category": category
    })
    .then((res) => onSubmitCallback())
}

...
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。