简体   繁体   English

反应自定义钩子状态改变但使用效果不重新渲染

[英]React custom hooks state change but useeffect not rerendering

I build custom hook for updating filter state that is shared between two component.我构建了自定义钩子来更新两个组件之间共享的过滤器状态。

Even when adding the filter as dependency on the useEffect the other component does not accept the state change.即使将过滤器添加为对 useEffect 的依赖,其他组件也不接受状态更改。 Why is that happening?为什么会这样?

later edit: I'm building a library where I want my users use the library's components without define special care of moving props to the correct component.稍后编辑:我正在构建一个库,我希望我的用户使用库的组件,而无需特别注意将道具移动到正确的组件。 I want it to work out of the box with out the need to define that.我希望它开箱即用,无需定义。

Here is my code:这是我的代码:

The custom hook:自定义钩子:

export default function SharedFilter() {
    const [filter, setFilter] = useState({filter: "Last 24 hours"});

    function setTheFilter(newFilter){
        setFilter({filter: newFilter.filter});
    }

    return [filter, setTheFilter];
}

The component that change the filter:改变过滤器的组件:

export default function TimeFilter() {

    const [filter, setFilter] = SharedFilter();

    return(
        <div>
            <select id="timeFilter" onChange={(event) => {
                setFilter({filter : event.target.value})
            }}>
                <option value="Last 24 hours">Last 24 hours</option>
                <option value="Last 48 hours">Last 48 hours</option>
                <option value="Last week">Last week</option>
                <option value="Last Month">Last Month</option>
                <option value="Last Year">Last Year</option>
            </select>
        </div>
    );
}

This is the component that the useEffect is not working:这是 useEffect 不起作用的组件:

export default function Chart() {

    const [filter, setFilter] = SharedFilter();

    useEffect(() => {
    }, [filter.filter]);

    return (
        <div>
            {filter.filter}
        </div>
    );
}

Hooks are not an angular services - they don't share a state. Hooks 不是一个有角度的服务——它们不共享一个状态。 You can't use setFilter in one component and use filter hoping to get the same value in another.您不能在一个组件中使用setFilter并使用filter希望在另一个组件中获得相同的值。 For that you should use context or pass it in props.为此,您应该使用上下文或在道具中传递它。

BTW, you should prefix your custom hooks with use, so useSharedFilter顺便说一句,你应该在自定义钩子useSharedFilter加上 use 前缀,所以useSharedFilter

如果是 globla 数据,则通过useContext使用上下文,因此您无需自定义新挂钩。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM