首页 > 解决方案 > 无法在 React 中的变量中设置值

问题描述

在我的 reactjs 应用程序中,我试图将值设置为变量数据,但它没有被分配。它应该从包含值的 nextProps.samples 分配,我可以登录我的浏览器控制台,这些值。

这是一段代码:

export default class GeofencingSamplesDL extends React.Component {
  // eslint-disable-line react/prefer-stateless-function

  state = {
    data: []
  };

  componentWillReceiveProps = nextProps => {
    let data = [];

    if (this.props.samples !== nextProps.samples) {

      nextProps.samples.forEach(sample => {
        data.push({
          Date: sample.timestamp,
          Semelle: sample.macAddress,
          Gateway: sample.deviceID,
          Pas: sample.steps,
          RSSI: sample.rssi,
          RawSteps: sample.rawSteps
        });        

        // Here values are visible as I print in console
        console.log("Sample " + JSON.stringify(sample));        



      });

      // Here values are not getting set
      this.setState({ data });      
    }

  };

有什么出路吗?提前致谢。

标签: reactjsreact-props

解决方案


a)componentWillReceiveProps在最新版本的 React 中被弃用/认为不安全。https://reactjs.org/docs/react-component.html#unsafe_componentwillreceiveprops。这可能是您的错误的原因。

b)getDerivedStateFromProps是为此目的首选的生命周期方法https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops

c) 或者,您可以将此组件重构为功能组件并使用 React 钩子


推荐阅读