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

React: re-fetch data in parent component when child component form submits

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

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

父组件(简化):

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

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

return (<ExpenseList expenses={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()..,然后将其作为 prop 提供给子级。在提交时调用它,作为 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())
}

...
}