forceUpdate强制更新,就是不需要经过阀门,直接对render进行更改
想要对其进行修改验证,可以先将阀门关闭,然后创建force对象
shouldComponentUpdate(){ console.log("shouldComponentUpdate"); return false; // 在这里开启TRUE那么就返回true,返回true那么就返回false }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="./"> </head> <body> <div id="test"></div> <script src="./react-resource/react.development.js"></script> <script src="./react-resource/react-dom.development.js"></script> <script src="./react-resource/babel.min.js"></script> <script src="./react-resource/prop-types.js"></script> <script type="text/babel"> class Count extends React.Component{ // 构造器初始化 state={count:0}; constructor(props){ console.log("constructor"); super(props); this.state={count:0}; } // 组件挂载完毕的输出 componentDidMount(){ console.log("componentDidMount"); } add=()=>{ const {count}=this.state; this.setState({count:count+1}); } // 组件将要挂载的钩子 componentWillMount(){ console.log("componentWillMount"); } death=()=>{ ReactDOM.unmountComponentAtNode(document.getElementById("test")) } componentWillUnmount(){ console.log("componentWillUnmount"); } // 创建组件阀门 shouldComponentUpdate(){ console.log("shouldComponentUpdate"); return false; // 在这里开启TRUE那么就返回true,返回true那么就返回false } // 组件将要更新的钩子 componentWillUpdaye(){ console.log("componentWillUpdate"); } // 组件已经更新完毕的钩子 componentDidUpdate(){ console.log("componentDidUpdate"); } force=()=>{ this.forceUpdate(); } render(){ console.log("render"); const {count}=this.state; return ( <div> <h2>当前求和为:{count}</h2> <button onClick={this.add}>点我加一</button> <button onClick={this.add}>点我加一</button> <button onClick={this.force}>强制更新</button> </div> ) } } ReactDOM.render(<Count/>,document.getElementById("test")); </script> </body> </html>