反应子组件在父组件中引起反应

时间:2021-01-22 14:43:45

标签: reactjs

我绝对是一个 React 菜鸟,但我已经进行了大量搜索,并且一直对这个基本原则缺乏了解。我有一个通过 create-react-app 创建的 React 应用程序,结构如下:

-Parent Component
    -Child Component with some statistic values
    -Child Component (Form with Submit Button)

当用户与 Form 子组件交互时,他们可能会混搭提交按钮,这会导致该组件中的代码进行 xhr 调用以与我的数据库交互。该交互的结果可能是其他子组件中的统计数据发生变化。当提交过程完成时,如何让 Stats 子组件重新获取它的数据?

现在我在 stats 组件中有获取代码,在表单组件中有提交代码。将所有代码强加给父级的答案是否可行?

我正在使用类组件,但如果这样更容易的话,可以转换为函数式组件。

3 个答案:

答案 0 :(得分:1)

我的建议是始终将组件保持为“尽可能愚蠢”,例如,表单只能是将调用父组件中的函数并在提交时发送数据以进行处理的表单本身,获取数据的fetch函数也可以在父组件中。

我将对功能组件进行抽象,我认为这些组件可以更快地阐述:

export default const **ParentComponent**=()=>{
const [dataFetched,setDataFetched]=useState([])//you will store your data here

const fetchData=()=>{
Apicall to get the data and store it in data
setDataFetched(response)
}

const handleSubmit=(formValues)=>{
-API call here with the post of data(formValues in the format you need)
-after api call call function fetch to refetch the data in your other child component
fetchData()
}

return(


 <ChildWithForm
    handleSubmit={handleSubmit}/>



  <Child2withdata
data={dataFetched}
>

希望它能给你一些提示,如果我能帮到你,请不要犹豫

答案 1 :(得分:0)

您可以将子组件的状态和功能移动到父组件。并通过所有作为道具。然后从 props 获取 submit 函数并在子组件中运行。

答案 2 :(得分:0)

如果您的数据在两个子组件之间共享,则应将其移至父组件。

通过这种方式,您可以在调用 XHR 后轻松地在父组件中设置新状态,并通过 prop 将该状态传递给 stats 组件。