0

我正在阅读 React 的书(初学者书),但我不太确定如何复制这个生命周期静态函数setDerivedStateFromProps

这是具有类方法的代码(但我需要使用功能方法):

public static getDerivedStateFromProps(
 props: RouteComponentProps,
 state: IState
) {
 const search = (new URLSearchParams(props.location.search)).get("search") || "";
 return {
 state.products,
 search
 } as IState;
}

我看到了 React 文档,他们给出了一个例子。我不完全确定它的含义以及它是否对我有用,但是我尝试将其用作参考并写了以下内容:

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吗?

4

0 回答 0