react-router4代码分割后、异步加载路由组件、根组件进行setState、会造成异步加载的路由组件重新渲染的问题
问题描述
react-router4代码分割后、异步加载路由组件、根组件进行setState、会造成异步加载的路由组件重新渲染的问题
问题出现的环境背景及自己尝试过哪些方法
https://lihqi.github.io/react...
参考代码
https://reacttraining.com/rea...
https://serverless-stack.com/...
相关代码
// 请把代码文本粘贴到下方(请勿用图片代替代码)
App.js
import React, { Component } from "react";
import { HashRouter as Router, Route, Link } from "react-router-dom";
// import Home from './Home'
import About from "./About";
import asyncComponent from "./AsyncComponent";
class App extends Component {
constructor() {
super();
this.state = {
count: 0
};
}
handleClick() {
let { count } = this.state;
this.setState({
count: count + 1
});
}
render() {
return (
<Router>
<div>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
</ul>
<div>{this.state.count}</div>
<div
style={{
width: "60px",
height: "60px",
background: "red"
}}
onClick={this.handleClick.bind(this)}
>
+
</div>
<hr />
<Route
exact
path="/"
component={asyncComponent(() =>
import(/* webpackChunkName: "Home" */ "./Home")
)}
/>
<Route path="/about" component={About} />
</div>
</Router>
);
}
}
export default App;
AsyncComponent.js
/**
* 分块加载
*/
import React, { Component } from "react";
export default function asyncComponent(importComponent) {
class AsyncComponent extends Component {
constructor(props) {
super(props);
this.state = {
component: null
};
}
async componentDidMount() {
const { default: component } = await importComponent();
this.setState({
component: component
});
}
render() {
const C = this.state.component;
return C ? <C {...this.props} /> : null;
}
}
return AsyncComponent;
}
Home.js
import React, { Component } from "react";
export default class Home extends Component {
componentDidMount(){
console.log('Home componentDidMount')
}
render() {
return (
<div>
<h2>Home</h2>
</div>
);
}
}
About.js
import React, { Component } from "react";
export default class About extends Component {
componentDidMount(){
console.log('About componentDidMount')
}
render() {
return (
<div>
<h2>About</h2>
</div>
);
}
}
你期待的结果是什么?实际看到的错误信息又是什么?
在demo里
点击加号改变跟组件的state
如果当前路由是Home(异步路由组件)
就会发现Home一直再重新渲染
如果当前路由是About(同步路由组件)
就不会有这个问题
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
https://github.com/ReactTrain...
还是自己使用的有问题