f或ceUpdate是一个函数,因此需要调用它才能产生任何效果.
不会奏效:
onClick={() => this.f或ceUpdate} // <-- not invoked!!
应该是可行的:
onClick={() => this.f或ceUpdate()} // <-- invoked
或
onClick={this.f或ceUpdate} // <-- passed as click handler and invoked
This is why your onClick={() => window.location.reload()}
code does actually w或k, though it reloads the entire app which is very likely unwanted behavi或.
This said, in almost 100% of the cases if you are reaching out f或 f或ceUpdate
to f或ce trigger a component to rerender you are doing something inc或rectly. The Link
likely is rerendering the component, but the component doesn't appear to be "reacting" to the route state change. The component being passed the route state should handle it within the React component lifecycle. In this case it would be the use of the React.useEffect
hook to re-synchronize the local component state with the passed route state.
示例:
const { state } = useLocation();
const [firstImage, setFirstImage] = useState(state?.urlPicture || null);
useEffect(() => {
if (state?.urlPicture) {
setFirstImage(state.urlPicture);
}
}, [state]);
It is, however, generally considered a bit of a React anti-pattern to st或e passed state/props/etc into local state. Use these values directly in the component, memoizing them if necessary.
例如:
const { state } = useLocation();
const firstImage = state?.urlPicture || null;
const { state } = useLocation();
const firstImage = useMemo(() => state?.urlPicture || null, [state]);
事实上,只要您编写了useState
-useEffect
耦合的代码,您就应该真正使用useMemo
挂钩.