【问题标题】:Trigger Child component method when prop changesprop 改变时触发 Child 组件方法
【发布时间】:2020-04-02 09:30:24
【问题描述】:

我正在尝试使子功能组件在父组件更改其状态中的值时更新,我将其作为道具传递给此子组件。

子组件正确“接收”值并显示道具值,但该方法不再运行。

子组件

import React from 'react'

const MyCustomTable = props => {
  const {
    data = [],
  } = props

  const finalData = getSalesData() //This is the method i want to run when the selectedMonth prop updates

  const getSalesData = () => {
    //It does some calculations with the prop called data
  }

  return (
    <Box>
        {JSON.stringify(props.selectedMonth.value)}
        <Table
            data={finalData}
        />
    </Box>
  )
}

SalesByFamilyBU.propTypes = {}

export default MyCustomTable

JSON.stringify 行正确显示更改,但我猜 getSalesData() 不会自动执行。

【问题讨论】:

  • 你怎么知道这个方法不会触发?尝试在getSalesData 函数中添加console.log()
  • 如果您在尝试调用函数之前定义了函数会有所帮助。

标签: reactjs


【解决方案1】:

虽然您可以使用一些生命周期方法或 useEffect 挂钩来实现您想要做的事情,但我更愿意使用函数式方法。

在您的示例中,finalData 是 props.dataprops.selectedMonth 的派生值。然后,您可以直接从这些 props 计算 finalData:

const MyCustomTable = props => {
    const {
        data = [],
    } = props;

    const filterData = (data, selectedMonth) => data.map(dataPoint => ({
        ...dataPoint,
        selected: dataPoint.month === selectedMonth,
    }); // or whatever, use your function logic here

    const finalData = filterData(data, props.selectedMonth.value);

    return (...);
};

如果您确实需要在每次数据发生变化时调用一个函数(例如在其他地方获取数据),您可以使用类似的方法:

const MyComponent = ({ data }) => {
    const [finalData, setFinalData] = useState([]);

    const myFunction = () => {
        const newData = ... // whatever you need to do
        setFinalData(newData);
    };

    useEffect(myFunction, [data]);

    return ...;
};

【讨论】:

    猜你喜欢
    • 2019-04-15
    • 2020-11-24
    • 2018-10-14
    • 2016-08-28
    • 2017-11-30
    • 1970-01-01
    • 2013-07-19
    • 1970-01-01
    • 2014-08-16
    相关资源
    最近更新 更多