我正在开发一个React项目。我想在点击重新加载按钮时重新加载一个组件。我按照下面给出的onClick函数进行了实现,但它却重新加载了整个窗口。我只想重新加载那个类组件,而不是整个窗口。有谁能帮我解决这个问题吗?
refreshPage() {
window.location.reload();
}
我正在开发一个React项目。我想在点击重新加载按钮时重新加载一个组件。我按照下面给出的onClick函数进行了实现,但它却重新加载了整个窗口。我只想重新加载那个类组件,而不是整个窗口。有谁能帮我解决这个问题吗?
refreshPage() {
window.location.reload();
}
我找到的最简单的方法是设置种子状态,并在呈现的组件的 key 属性中使用该状态。现在每当种子更改时,组件将重新加载。
const [seed, setSeed] = useState(1);
const reset = () => {
setSeed(Math.random());
}
<Component key={seed}/>
<Button onClick={reset}>Reset</Button>
无论何时按下Reload按钮,现在我需要的组件都将重新渲染。如果您只想重新加载组件的数据,请使用useEffect Hook:
useEffect(() => {
fetchData();
}, [data]);
// fetchData() is called whenever data is updated.
class YourComponent extends Component {
state = {
reload: false
};
refreshPage = () => {
this.setState(
{reload: true},
() => this.setState({reload: false})
)
}
}
这个可能有点低级,但应该能够起作用。虽然我还没有测试过。
componentDidMount
吗? - GaurangarefreshPage() {
window.location.reload(false);
}
参考链接:https://upmostly.com/tutorials/how-to-refresh-a-page-or-component-in-react
exampleFunction = () => {
/** Do your job here */
}
componentDidMount(){
/** your code */
this.exampleFunction ();
/** your code */
}
refreshPage(){
this.exampleFunction ();
}
componentDidUpdate
、componentDidMount
或构造函数中的代码,只会重新渲染。 - skyboyerwindow.location.reload(); 会重新加载当前文档,就像浏览器中的刷新按钮一样,并且不会像 AJAX 一样进行任何部分重新渲染。要通过在 React 中使用 setState 来实现此目的。
以下是工作示例:
import React from "react";
class RefreshComponent extends React.Component {
constructor(props) {
super(props);
this.state = { name: "React Component reload sample" };
}
submit() {
this.setState({ name: "React Component Updated - " + new Date() });
}
render() {
return (
<div>
{this.state.name}
<br />
<button
onClick={() => {
this.submit();
}}
>
Submit
</button>
</div>
);
}
}
export default RefreshComponent;
reload
的单独上下文。key
props(到任何其他值,可能只是随机字符串),整个分支将被重新创建,包括对componentDidMount
的调用。这被称为“按键道具重置状态”技术。但这既不安全也不是真正灵活的方式。最好避免这种情况,直到您真正不关心可维护性(或者将其用作临时解决方案...但通常“临时解决方案”会持续存在于应用程序存在期间)。您可以查看另一个帖子: 不调用setState如何强制React组件重新渲染?
这是最佳答案:
在类组件中,您可以调用
this.forceUpdate()
来强制重新渲染。文档: https://facebook.github.io/react/docs/component-api.html
在函数组件中,没有等价于
forceUpdate
的方法,但是您可以使用useState hook构建一种强制更新的方式。
useEffect(() => {
// Get the reloaded value from localStorage
const storedValue = localStorage.getItem("reloadWindow");
// Check if storedValue is null or undefined or 0
if (
storedValue === null ||
storedValue === undefined ||
storedValue === "0" // this is because I had set to 0 when i logged out
) {
window.location.reload();
// Set the value in localStorage
localStorage.setItem("reloadWindow", JSON.stringify(1));
}
}, []);
componentDidMount
方法?如果是的话,我只看到一个可能的解决方案,那就是更改你想要“更新”的部分中最顶层元素的key
属性。 - skyboyer