您可以在功能组件(反应)中使用useEffect复制静态setDerivedStateFromProps吗?

时间:2020-07-13 11:19:41

标签: reactjs react-hooks react-lifecycle-hooks

我正在读一本关于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一样工作?

0 个答案:

没有答案