如果连接到未更改的存储,React componentDidUpdate 方法不会在继承的 props 更改时触发

2023-11-21

我希望我的组件知道某些库是否已加载。要知道,从任何上下文我都将其连接到我的商店的“库”减速器到我的组件。 我还向它传递了一个配置对象this.props.dataObject来自调用该组件的父级。像这样:

class GoogleButton extends Component {
    render() {
        if (this.props.libraries.google) {
            return <a id='sharePost' className='google_icon'></a>
        } else {
            return null
        }
    }

    componentDidUpdate() {
        gapi.interactivepost.render('sharePost', this.props.dataObject)
    }
}

function mapStateToProps(state) {
    return { libraries: state.libraries }
}

export default connect(mapStateToProps)(GoogleButton)

处理库状态的reducer是这样的:

let newState = {...state}
newState[action.libraryName] = action.state
return newState 

当我更改库状态时componentDidUpdate作品。问题是当我更改父级继承的道具时this.props.dataObject。在这种情况下, componentDidUpdate 不会触发。如果我删除connect从组件来看,它按预期工作。我在这里遗漏了一些东西?


最有可能的是你的一些 props 在组件之外发生了变异。
例如,您可能会像这样渲染组件:

class Parent extends Component {
  constructor() {
    super()
    this.state = { libraries: {} }
  }

  handleClick() {
    // MUTATION!
    this.state.libraries.google = true

    // Normally this forces to update component anyway,
    // but React Redux will assume you never mutate
    // for performance reasons.

    this.setState({ libraries: this.state.libraries })
  }

  render() {
    return (
      <div onClick={() => this.handleClick()}>
        <GoogleButton libraries={this.state.libraries} />
      </div>
    )
  }
}

因为 Redux 应用程序处理不可变数据,connect() uses 浅层相等检查其道具可以避免不必要的重新渲染。但是,如果您在应用程序中使用突变,这将不起作用。

您有两个选择:

不要改变任何东西

这是最好的选择。例如,而不是类似的东西

  handleClick() {
    this.state.libraries.google = true
    this.setState({ libraries: this.state.libraries })
  }

你可以写

  handleClick() {
    this.setState({
      libraries: {
        ...this.state.libraries,
        google: true
      }
    })
  }

这样我们就创建了一个新对象connect()不会忽略更改后的引用。 (我正在使用对象扩展语法在这个片段中。)

禁用性能优化

更糟糕的选择是完全禁用由connect()。然后,即使您在父级中改变它们,您的道具也会更新,但您的应用程序会变慢。为此,请替换

export default connect(mapStateToProps)(GoogleButton)

with

export default connect(mapStateToProps, null, null, { pure: false })(GoogleButton)

除非绝对必要,否则不要这样做。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如果连接到未更改的存储,React componentDidUpdate 方法不会在继承的 props 更改时触发 的相关文章

随机推荐