Javascript 将重新渲染限制为功能组件中的特定状态更改

Javascript 将重新渲染限制为功能组件中的特定状态更改,javascript,reactjs,typescript,Javascript,Reactjs,Typescript,如果我有一个具有三种不同状态的组件,并且我只想在该组件中的一种特定状态发生更改时重新渲染该组件,我将如何执行该操作 下面我提供了一个代码示例。假设我只希望在调用setSecondState()时重新呈现此组件,而不是在调用setFirstState()或setThirdState()时 const ExampleComponent = () => { const [firstState, setFirstState] = React.useState(0); const

如果我有一个具有三种不同状态的组件,并且我只想在该组件中的一种特定状态发生更改时重新渲染该组件,我将如何执行该操作

下面我提供了一个代码示例。假设我只希望在调用setSecondState()时重新呈现此组件,而不是在调用setFirstState()或setThirdState()时

const ExampleComponent = () => {
     const [firstState, setFirstState] = React.useState(0);
     const [secondState, setSecondState] = React.useState(false);
     const [thirdState, setThirdState] = React.useState("");

     return (
          <div>
                Rendered
          </div>
     );
}
const ExampleComponent=()=>{
常量[firstState,setFirstState]=React.useState(0);
const[secondState,setSecondState]=React.useState(false);
const[thirdState,setThirdState]=React.useState(“”);
返回(
提供
);
}

不要将它们放在状态use ref中。您可以通过更新ref.current来更新ref值,这不会导致重新渲染

const ExampleComponent = () => { 

     const firstRef = React.useRef(0);
     const [secondState, setSecondState] = React.useState(false);
     const secondRef = React.useRef("");

     const someFunction = () => {
         firstRef.current = 10;
         secondRef.current = "foo";
     }

     return (
          <div>
                Rendered
          </div>
     );
}
const ExampleComponent=()=>{
const firstRef=React.useRef(0);
const[secondState,setSecondState]=React.useState(false);
const secondRef=React.useRef(“”);
常量someFunction=()=>{
第一参考电流=10;
secondRef.current=“foo”;
}
返回(
提供
);
}
您可以使用生命周期功能。 这将返回一个布尔值,告诉您是否响应渲染

在下面的示例中,当v1值更改时,它不会触发重新渲染,而更改v2会触发重新渲染

const ExampleComponent = () => { 

     const firstRef = React.useRef(0);
     const [secondState, setSecondState] = React.useState(false);
     const secondRef = React.useRef("");

     const someFunction = () => {
         firstRef.current = 10;
         secondRef.current = "foo";
     }

     return (
          <div>
                Rendered
          </div>
     );
}
类应用程序扩展了React.Component{
状态={
v1:0,
v2:0
}
shouldComponentUpdate(下一步,下一步状态){
log('v1:',nextState.v1',v2:',nextState.v2);
返回this.state.v1===nextState.v1
}
render(){
const{v1,v2}=this.state;
返回(
this.setState(({v1})=>({v1:v1+1}))}>{`增加但不呈现:${v1}`}
this.setState(({v2})=>({v2:v2+1}))}>{`Increase and render:${v2}}} ) } } ReactDOM.render(,document.getElementById('root'))