反应上下文重置使用者状态

时间:2020-03-19 19:11:27

标签: javascript reactjs context-api

我正在尝试使用React Context API将状态数据从父级组件传递到深层嵌套的子级。

父级是类组件,子级是函数。

当我从子级中使用通过Context传递的函数更新父级状态时,父级状态已成功更新,但随后将子级的本地状态重置为初始值。

父母:

 export class ObjectLinking extends Component {
        constructor(props) {
            super(props);
            this.state = {
                setCurrentlyDisplayed: this.setCurrentlyDisplayed,
                currentlyDisplayed: []
            };
        }

        [...]

        render() {
            return (
                <ObjectLinkingContext.Provider value={this.state}>
{//Panel body will contain deep nested child that is connected to context}
                   <PanelBody />
                </ObjectLinkingContext.Provider>
            );
        }
    }

孩子:

  import ObjectLinkingContext from '../../context/ObjectLinkingContext';
    const AssetListFilters = ({ assets, filtersModel }) => {
        const [searchByNameVal, setSearchByNameVal] = useState([]);
        const panelContext = useContext(ObjectLinkingContext);

        useEffect(() => {
            filterBySearchNameVal();
        }, [searchByNameVal]);

        const filterBySearchNameVal = () => {
            if (searchByNameVal.length) {
                const { setCurrentlyDisplayed } = panelContext;
                const { value: searchedId } = searchByNameVal[0];
                const searchedAsset = assets.filter(asset => asset.assetId === searchedId) || [];
                setCurrentlyDisplayed(searchedAsset);
            }
        };

        return (
                        <Autocomplete
                            onChange={val => setSearchByNameVal(val)}
                        />

      );
    };

找到here完整的Parent.js和VeryDeepChild.js组件

0 个答案:

没有答案