react项目中页面跳转、刷新及获取网络状态
// 页面跳转 window.location.href = 'http://speedtest.wangxiaotong.com/' // 页面刷新 window.location.reload() // 获取当前网络状态,只能判断用户电脑有没有断网(包括无线和有线),有网为true,没有网为false navigator.onLine
react强制页面刷新
在react中,state和props数据更新,就会重新render,但是当层级过深时,可能就不会触发渲染,这时候就要用到
this.forceUpdate();
说明:
默认情况下,当组件的state或props改变时,组件将重新渲染。如果你的render()方法依赖于一些其他的数据,你可以告诉React组件需要通过调用forceUpdate()重新渲染。
调用forceUpdate()会导致组件跳过shouldComponentUpdate(),直接调用render()。这将触发组件的正常生命周期方法,包括每个子组件的shouldComponentUpdate()方法。
forceUpdate就是重新render。有些变量不在state上,当时你又想达到这个变量更新的时候,刷新render;或者state里的某个变量层次太深,更新的时候没有自动触发render。这些时候都可以手动调用forceUpdate自动触发render
//Sub.js class Sub extends React.Component{ construcotr(){ super(); this.name = "yema"; } refChangeName(name){ this.name = name; this.forceUpdate(); } render(){ return (<div>{this.name}</div>); } } App.js class App extends React.Component{ handleClick(){ this.subRef.refChangeName("yemafuren"); } render(){ return (<div> <Sub ref={(sub)=>{this.subRef = sub;}} /> <button onClick={this.handleClick}>click</button> </div>); } }
相关推荐:react教程
以上就是react怎么刷新页面?的详细内容,更多请关注0133技术站其它相关文章!