在React中强制重新渲染的4 种方式案例代码
作者:大海里的一条鱼.
这篇文章主要介绍了在React中强制重新渲染的4 种方式,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧
1.在 state 改变时重新渲染组件
React 组件在每次 state 变化时都会运行 render() 方法。
class App extends React.Component {
componentDidMount() {
this.setState({});
}
render() {
console.log('render() method')
return <h1>Hi!</h1>;
}
}在上面的例子中,在组件挂载完成之后更新了 state。
也可以在事件监听器中触发重新渲染组件,例如 click 事件里。
class App extends React.Component {
state = {
mssg: ""
};
handleClick = () => {
this.setState({ mssg: "Hi there!" });
};
render() {
console.log("render() method");
return (
<>
<button onClick={this.handleClick}>Say something</button>
<div>{this.state.mssg}</div>
</>
);
}
}以上都会输出如下:
render() method
render() method
2.在 props 改变时重新渲染组件
class Child extends React.Component {
render() {
console.log('Child component: render()');
return this.props.message;
}
}
class App extends React.Component {
state = {
mssg: ""
};
handleClick = () => {
this.setState({ mssg: "Hi there!" });
};
render() {
return (
<>
<button onClick={this.handleClick}>Say something</button>
<Child message={this.state.mssg} />
</>
);
}
}上述例子中 <Child /> 组件不含有 state,但它接收了一个 prop 名为 message。
点击按钮后,会更新 <Child /> 组件,会引起 render() 再次执行。
Child component: render() Child component: render()
3.借助 key prop 重新渲染
上述更新 state 和 props 的操作不会引起组件的重新挂载/卸载,只会重新调用 render() 方法。有时候对于一些逻辑复杂的组件,我们需要重新挂载/卸载操作,以便重新渲染内容。
class Child extends React.Component {
componentWillUnmount() {
console.log("will unmount");
}
render() {
console.log("Child component: render()");
return this.props.message;
}
}
class App extends React.Component {
state = {
messages: [
{ id: 1, title: "Hello from Beijing", content: "Welcome to Beijing" },
{ id: 2, title: "Hello from London", content: "Welcome to London" },
{ id: 3, title: "Hello from Tokyo", content: "Welcome to Tokyo" }
],
activeId: null
};
render() {
const { messages, activeId } = this.state;
return (
<>
<ul>
{messages.map((item) => (
<li
key={item.id}
onClick={() => {
this.setState({ activeId: item.id });
}}
>
{item.title}
</li>
))}
</ul>
<Child
key={activeId}
message={
activeId
? messages.find((item) => item.id === activeId).content
: ""
}
/>
</>
);
}
}上述的这个例子,当用户点击标题时,我们想要重新挂载/卸载整个子组件,这时可以在子组件上增加一个 key 属性,这样便实现了目的。可以看到每次点击后,都会执行 componentWillUnmount() 方法。
4.强制重新渲染
不建议采用此方式,建议采用更新 props 和 state 的方式。
class App extends React.Component {
handleClick = () => {
// force a re-render
this.forceUpdate();
};
render() {
console.log('App component: render()')
return (
<>
<button onClick={this.handleClick}>Say something</button>
</>
);
}
}到此这篇关于在 React 中强制重新渲染的 4 种方式的文章就介绍到这了,更多相关React 重新渲染内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
