我已经解决了我自己的问题,但我不知道发生了什么,为什么它的工作.

我有一个Link组件,链接到它当前所在的相同页面,但针对的是不同的产品.同样的组件,但展示的是不同的产品.

<Link to={directUrl} onClick={() => this.forceUpdate} state={{ urlPicture: picture }}>

注意<Link>是在一个子组件中,而不是它自己路由到的主组件中.

因为它路由到相同的页面,所以Link不会自动刷新页面.为了解决这个问题,我添加了onClick={() => this.forceUpdate},但现在我的状态不能正常通过.我用另一个组件中的以下代码行判断了这一点.

location = useLocation()
const [ firstImage, setFirstImage ] = useState(location.state?.urlPicture || null)
console.log(`here is ${mainPicture}`) //mainPicture is just a string

然而,当我用onClick={() => window.location.reload()}替换onClick={() => this.forceUpdate}时,我的状态确实会正确地通过Link.

我知道2和this.forceUpdate之间是有区别的,但据我所知,它应该刷新组件并更新其状态.我不明白为什么这还不够,老实说,我也不知道为什么它会这样运作.

推荐答案

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挂钩.

Javascript相关问答推荐

如何访问react路由v6加载器函数中的查询参数/搜索参数

具有相同参数的JS类

GrapeJS -如何保存和加载自定义页面

在带有背景图像和圆形的div中添加长方体阴影时的重影线

如何避免页面第一次加载时由于CSS样式通过JavaScript更改而出现闪烁

编辑文本无响应.onClick(扩展脚本)

是什么导致了这种奇怪的水平间距错误(?)当通过JavaScript将列表项元素追加到无序列表时,是否在按钮之间?

为什么我的getAsFile()方法返回空?

向数组中的对象添加键而不改变原始变量

为什么在函数中添加粒子的速率大于删除粒子的速率?

我想使用GAS和HTML将从Electron 表格中获得的信息插入到文本字段的初始值中

如何根据输入数量正确显示alert ?

在SuperBase JS客户端中寻址JSON数据

本地损坏的Java脚本

如何在Jest中模拟函数

是否设置以JavaScript为背景的画布元素?

限制数组中每个元素的长度,

脚本语法错误只是一个字符串,而不是一个对象?

需要刷新以查看Mern堆栈应用程序中的更改

为什么我的Reaction组件不能使用createBrowserRouter呈现?