相关疑难解决方法(0)

我该如何在React中强制使用钩子重新渲染组件?

考虑下面的钩子示例

   import { useState } from 'react';

   function Example() {
       const [count, setCount] = useState(0);

       return (
           <div>
               <p>You clicked {count} times</p>
               <button onClick={() => setCount(count + 1)}>
                  Click me
               </button>
          </div>
        );
     }
Run Code Online (Sandbox Code Playgroud)

基本上,我们使用this.forceUpdate()方法强制组件在React类组件中立即重新呈现,如下例所示

    class Test extends Component{
        constructor(props){
             super(props);
             this.state = {
                 count:0,
                 count2: 100
             }
             this.setCount = this.setCount.bind(this);//how can I do this with hooks in functional component 
        }
        setCount(){
              let count = this.state.count;
                   count = count+1;
              let count2 = this.state.count2;
                   count2 = count2+1;
              this.setState({count});
              this.forceUpdate();
              //before below …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs react-native react-hooks

38
推荐指数
11
解决办法
3万
查看次数

标签 统计

javascript ×1

react-hooks ×1

react-native ×1

reactjs ×1