this.props 属性的问题,即使它们存在

Issue with this.props properties not existing even though they do

本文关键字:存在 props 属性 问题 this      更新时间:2023-09-26

对,这是一个地狱般的名字。但我就是想不出更好的标题。

问题如下。

在 React 中,在componentWillMount期间,我将状态启动到 null ,然后在通过 ajax 从服务器中提取数据后进行更新。

结构如下所示:

  componentWillMount() {
    this.state = { calculator: {} };
  initCalculator()
    .then(calculator => {
      this.setState({ calculator });
    })
    .catch(err => {
      console.log(err);
    });
  }

数据本身被拉到这里:

  function initCalculator() {
    const promise = new Promise((resolve, reject) => {
      const instance = parseInstance();
      const compId = Wix.Utils.getOrigCompId();
      axios.get(`/api/calculator?instance=${instance}&compId=${compId}`)
        .then(res => {
          resolve(res.data);
        })
        .catch(err => {
          reject(err);
        });
    });
    return promise;
  }

res.data是包含来自服务器的数据的响应对象。

然后,这些数据将传递到状态,如您在上面看到的那样。

然后,此状态数据将传递给另一个元素,如下所示:

<Settings tab="Settings" calculator={ this.state.calculator } onUpdate={ this.settingsUpdate.bind(this) }/>

但是,数据不会在"设置"选项卡的另一端"解析"。

每当我尝试访问计算器对象深处的属性时,它总是向我抛出错误。

cannot read property settings of null

这可以在这里看到

const name = this.props.calculator.settings ? this.props.calculator.settings.name : '';

因此,如果我尝试访问calculator.settings.name,它会向我抛出类似的错误。

此外,const name 总是设置为 '' ,即使在第二次重新渲染期间,当数据可能已经可用时,因为状态已更新,从而提示在子元素中重新渲染。

我理解为什么会这样。至少有点。对象在解析之前传递,因此在第二次状态更改期间(即this.setState({ calculator });在状态完全更新之前调用重新渲染。至少我是这么认为的。

如果我console.log(this.props.calculator),我可以看到所有这些数据。但是由于控制台.log,单击箭头展开详细信息后,它会同时解析数据。

如果我这样做JSON.stringify(this.props.calculator),数据都显示在那里可用。现在我知道我可以使用JSON.stringifyJSON.parse来解决这个问题。但这只是解决我可能自己创造的此类问题的一种愚蠢方法。

我知道对象通过引用工作。所以我认为问题出在初始 ajax get 请求或 setState 方法的某个地方。

也许有敏锐眼光的人能够看到这里的问题所在。但此时我只是把头撞在墙上。

constructor而不是componentWillMount中设置您的状态。在 componentDidMount 上进行 ajax 调用,并在请求成功时更新状态。

     constructor(props) {
       super(props);
       this.state = {
        data: null,
       }
     }
     componentWillMount() {
     }
     updataStateFromCompletedAjax(data) {
      this.setState({
       data: data
      })
     }