知道地图状态道具何时更新

时间:2019-10-30 07:49:29

标签: reactjs redux

我在React和Redux Start Kid中有以下应用程序

在组件中,我使用了一系列与同一商店Items相关的选择器:

const mapStateToProps = (state: RootState) => ({
    itemsLoading: ItemsSelectors.getItemsIsLoading(state),
    items: ItemsSelectors.getCurrentItemList(state),
    fields: ItemsSelectors.getCurrentItemFields(state),
    columns: ItemsSelectors.getCurrentItemColumns(state)
})

当存储值更改时,我想通过对数据进行一些计算来更新组件状态。

我正在使用以下功能

UNSAFE_componentWillUpdate(nextProps) {
    const displaybleTable = this.getDisplaybleTable(nextProps);
    this.setState({
        items : displaybleTable.items,
        columns : displaybleTable.columns
    })
}

因此,每次商店更改时,我都会更新,并且会更新组件状态。

问题在于,由于我更新了组件状态,因此我正在循环使用此函数。

此外,我认为它看起来有点奇怪。

是否有办法知道组件中存储值何时更新,以便该组件可以进行一些个人数据操作?

1 个答案:

答案 0 :(得分:1)

您使用哪个版本的react?

如果我对您的理解正确并假定使用的是16.8+版本,则可以使用useEffect() hook来实现。我假设您的组件已使用来自'react-redux'的connect()连接到商店。然后看起来像这样:

const MyComponent = (props) => {

    useEffect(() => {
        const displaybleTable = this.getDisplaybleTable(/* arguments */);
        this.setState({
            items : displaybleTable.items,
            columns : displaybleTable.columns
        })
    }, [props.items])

    const getDisplayableTable = (/* args: any */) => {
        return ...
    }

    ...
}

export const MyConnectedComponent = connect(
    (state: RootState) => ({
        itemsLoading: ItemsSelectors.getItemsIsLoading(state),
        items: ItemsSelectors.getCurrentItemList(state),
        fields: ItemsSelectors.getCurrentItemFields(state),
        columns: ItemsSelectors.getCurrentItemColumns(state)
    }),
    {
        // dispatchProps ... 
    },
    (stateProps: any, dispatchProps: any, ownProps: any) => ({
        itemsLoading: stateProps.itemsLoading,
        items: stateProps.items,
        fields: stateProps.fields,
        columns: stateProps.columns
    })
)(MyComponent)

useEffect的第二个参数定义useEffect()何时调用第一个参数,它是一个函数。因此,每次在商店中更新“ items”时,更新都会触发useEffect,后者将运行代码并设置组件的状态。

编辑:

如果商店中的某些值发生更改,则不会调用

ComponentWillUpdate(nextProps)。仅当您传递给组件的道具发生更改时,才调用ComponentWillUpdate:

export const SomeOtherComponent = (props: any) => {
    return (
        <MyComponent prop1={val1} prop2={val2} />
    )
}

如果val1和val2更改,则将调用MyComponent的ComponentWillUpdate(据我所知,但我不确定)。