道具更改时触发子组件方法

时间:2020-04-02 09:30:24

标签: reactjs

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

子组件正确“接收”该值并显示prop值,但是该方法不会再次运行。

子组件

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()不会自动执行。

1 个答案:

答案 0 :(得分:0)

虽然您可以使用某些生命周期方法或useEffect钩子来实现您想要的功能,但我宁愿使用功能性方法。

在您的示例中,finalData是props.dataprops.selectedMonth的派生值。然后,您可以直接从这些道具计算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 ...;
};