钩子如何更新传递给组件的道具?

How can hooks update the props passed to component?

我有一个正在传递 prop 的组件,我需要在 prop 的值更改时更新该组件。

我已经尝试使用 useEffect 挂钩来观察道具和 prop.propIWantToChange 但我无法在组件呈现后将更新传递给组件。

App.js

let tracker = true;

const handleChangeTracker = () => {
  tracker = !tracker
}

const App = props => {
  <React.Fragment>
    <button onClick={handleChangeTracker} >Change</button>
    <Component1 active={tracker} />
    <Component2 />
    <Component3 />
    <Component4 />
  </React.Fragment>
}

Component1.js

const Component1 = props => {

  useEffect(() => {
    console.log(props.active)
  }, [props.active])

  return (  
    <div>{props.active && "You see this when its true"}</div>  
  )
}

点击按钮时,我希望tracker的值在true和false之间切换。然后我希望它将该新值传递给 Component1。目前它将更改值(我通过控制台日志跟踪它)但它不会将新值传递给组件。

该值未传递给子组件,因为您的 'tracker' 变量未存储在状态中。 state 值的变化会触发新的渲染,而不是 variable 值的变化。

因此,当 'tracker' 在 'handleChangeTracker' 中更新时,它不会触发新的渲染,因此新值不会传递给子组件,因此不会对子组件进行新的渲染。

解决方法是在'tracker'中保存状态,然后在'handleChangeTracker'中更新状态。

this.state = { tracker = true; }

const handleChangeTracker = () => {
  this.setState({
            tracker: !tracker
        })
}

const App = props => {
  <React.Fragment>
    <button onClick={handleChangeTracker} >Change</button>
    <Component1 active={this.state.tracker} />
    <Component2 />
    <Component3 />
    <Component4 />
  </React.Fragment>
}