我正在读一本关于React的书(入门书),但我不确定如何复制此生命周期静态函数setDerivedStateFromProps
这是使用类方法的代码(但我需要使用函数方法):
public static getDerivedStateFromProps(
props: RouteComponentProps,
state: IState
) {
const search = (new URLSearchParams(props.location.search)).get("search") || "";
return {
state.products,
search
} as IState;
}
我看到了the React documentation,他们给了一个例子。我不完全确定这意味着什么以及它是否对我有用,但是我尝试将其用作参考,并且我写了这样的话:
const [state, setState] = useState(defaultState);
const [previousState, setPreviousState] = useState(null);
if (state !== previousState) {
const search = (new URLSearchParams(props.location.search)).get("search") || "";
setState({state.products, search} as IState);
setPreviousState(state);
}
以上代码是否可以像setDerivedStateFromProps
那样工作?上面的代码和使用useEffect
这样的代码有什么区别:
const [state, setState] = useState(defaultState);
useEffect(() => {
const search = (new URLSearchParams(props.location.search)).get("search") || "";
setState({state.products, search} as IState);
}, [ props.location.search ]);
此功能是否可以像setDerivedStateFromProps
一样工作?