【问题标题】:How to set props before render in React如何在 React 渲染前设置 props
【发布时间】:2019-02-28 06:15:16
【问题描述】:

谁能告诉我为什么,当我在 componentWillMount() 方法中设置状态时,render() 中的一个函数在设置状态之前运行,即

这是我的应用程序:

class App extends Component {
  constructor(props){
    super(props);
    this.state={
      x : 50,
      y : 100,
      width : 200,
      height : 300
    }
    this.handleDuplicate = this.handleDuplicate.bind(this);
  }

  handleDuplicate(newDims){
    this.setState({newDims : newDims})
  }

  render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome to React</h1>
        </header>
        <svg id="svgOne" width="5000" height="3000">
          <NewRect 
            {...this.state}
            handleDuplicate={this.handleDuplicate}
          />
        </svg>
      </div>
    );
  }
}

这是我的组件,NewRect:

import React, { Component } from 'react';

class NewRect extends Component {
  componentWillMount(){
    let { x, y, width, height } = this.props
    let newDims = {
      x : x + 30,
      y : y + 30,
      width : width - 50,
      height : height + 50
    }
    this.props.handleDuplicate(newDims);
  }

  render() {
    console.log(this.props);
    return (
          <rect 
            x={this.props.x} 
            y={this.props.y} 
            width={this.props.width} 
            height={this.props.height} 
            fill="black" 
          />
    );
  }
}

export default NewRect;

据我所知,componentWillMount() 的全部意义在于完成所有需要在 render() 之前完成的操作。

【问题讨论】:

  • 仅供参考,在 eact 16 中,componentWillMount 被认为是遗留的,并且可能会在某些时候消失,正是因为 ots 的正确用法一直被误解。

标签: reactjs components state


【解决方案1】:

setState 是异步的,因此您不能假设使用新状态调用渲染。

您可以做的是创建一个名为“正在加载”或类似名称的状态变量,将其初始值设置为true,并在componentWillMount中将其设置为false。

在渲染中,当加载仍然为真时,您将显示一个微调器。

顺便说一句,我发现很难理解您的代码,但我确信 React 比我更聪明 :) 您将父级的状态作为道具传递给您的子组件,该子组件在父组件中运行一个可能会更改父级状态的函数,该状态作为道具传递......这不是最简单的事情,我希望它可以工作:)

我会尝试考虑一种更简单的方法来做到这一点,但我并不总是正确的,远非如此......

【讨论】:

    【解决方案2】:

    setState 是异步的。我怀疑发生了什么:

    1. App.render() 被调用
    2. NewRect 被实例化
    3. NewRect.componentWillMount() 被调用
    4. App.handleDuplicate() 被调用
    5. App.setState() 被调用
    6. NewRect.render() 被调用
    7. App.setState() 更改已执行
    8. App.render() 被称为
    9. 新的道具被传递给NewRect
    10. NewRect.render() 被调用

    最终这应该无关紧要。如果是这样,请考虑在NewRect 中镜像状态或在setState 上使用回调。如果您的模式依赖于同步渲染,您可能需要重新审视您的架构。 React 正在移动 toward fully asynchronous rendering

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-30
      • 1970-01-01
      • 1970-01-01
      • 2020-03-10
      • 1970-01-01
      • 1970-01-01
      • 2020-07-31
      • 2021-07-20
      相关资源
      最近更新 更多