简体   繁体   English

如何将所有数组值存储到单个 React state 中?

[英]How to store all array values into a single React state?

I have a config file which contains an array that gets data from redux我有一个配置文件,其中包含一个从 redux 获取数据的数组

"datapath": [
  "common.registration.rgsnInfoRs[0].value",  // street name
  "common.registration.rgsnInfoRs[1].value",  // city
  "common.registration.rgsnInfoRs[2].value",  // state
  "common.registration.rgsnInfoRs[3].value"   // zip code
]

In my react component, when I tried to render the data from this array it only returns back the data for the zip code.在我的反应组件中,当我尝试从该数组呈现数据时,它只返回 zip 代码的数据。 How can I make my component render all of index data in my render method?如何让我的组件在我的渲染方法中渲染所有索引数据?

constructor(props) {
  super(props);
  this.state = {
    // data: '',
    data: []
  }
}
componentDidMount(){
  if(_.get(this.props, 'datapath')){
    _.map(this.props.datapath, (item, i) => {
      let data=_.get(this.props.state,`i`);
      this.setState({data})
    })
  }
}

// static getDerivedStateFromProps(props, state) {
//   if(_.get(props, 'datapath')){
//     _.map(props.datapath, (item, i) => {
//       let data=_.get(props.state,item);
//       state.data = data;
//     }) 
//   }
// }


static getDerivedStateFromProps(props, state) {
    if(_.get(props, 'datapath')){
      _.map(props.datapath, (item, i) => {
        let data=_.get(props.state,item);
        this.setState((prevState) => {
          return { data: [...prevState.data, data] }
         });
      })
    }
  }

render() {
  const {type, label} = this.props;
  return (
    type === "grid" ? (
      <Grid.Column style={style}>
        <strong>{label ? `${label}:` : null}</strong> {this.state.data}
      </Grid.Column>
    ) : (
      null
    )
  )
}

Your initial data type for this.state.data is an array. this.state.data的初始数据类型是一个数组。 But in the following line, it gets the value of the item (in this case, it's either street name, city, state or zipcode).但在下一行中,它获取项目的值(在本例中,它是街道名称、城市、state 或邮政编码)。 These values are string type and override the this.state.data datatype from array to string.这些值是字符串类型并覆盖从数组到字符串的this.state.data数据类型。

let data=_.get(props.state, `i`); // This is incorrect

You should append the value in the state data instead of assign in componentDidMount您应该 append state 数据中的值,而不是在componentDidMount中分配

componentDidMount() {
  if(_.get(this.props, 'datapath')){
    _.map(this.props.datapath, (item, i) => {
       let data=_.get(this.props.state,`i`);
       this.setState((prevState) => {
          return { data: [...prevState.data, data] }
        });
    })
  }
}

Now Let's look at getDerivedStateFromProps function.现在让我们看看getDerivedStateFromProps function。 This is a static function and you can not use this inside a static function.这是一个 static function 并且您不能在 static ZC1C425268E683794F1A14 中使用this According to the react docs , this function returns the updated state.根据反应文档,这个 function 返回更新的 state。

static getDerivedStateFromProps(props, state) {
const newData = [];
if(_.get(props, 'datapath')) {
  _.map(props.datapath, (item, i) => {
    let data=_.get(props.state,item);
    newData.push(data);
  });
  return { data: newData };
}

} }

I think that you are not asking the right questions.我认为你没有问正确的问题。 It is generally a bad idea to store data from props in state because it can lead to stale and outdated data.将 props 中的数据存储在 state 中通常是一个坏主意,因为它可能导致数据过时和过时。 If you can already access it from props, then you don't need to also have it in state.如果您已经可以从道具访问它,那么您不需要在 state 中有它。

Your component receive a prop state which is an object and a prop datapath which is an array of paths used to access properties on that state .您的组件收到一个道具state ,它是一个 object 和一个道具datapath ,它是用于访问该state上的属性的路径数组。 This is already weird and you should look into better patterns for accessing redux data through selector functions.这已经很奇怪了,您应该研究通过选择器函数访问 redux 数据的更好模式。

But if we can't change that, we can at least change this component.但是如果我们不能改变它,我们至少可以改变这个组件。 You can convert an array of paths to an array of values with one line of code:您可以使用一行代码将路径数组转换为值数组:

const data = this.props.datapath.map( path => _.get(this.props.state, path) );

All of the state and lifecycle in your component is unnecessary.您的组件中的所有 state 和生命周期都是不必要的。 It could be reduced to this:可以简化为:

class MyComponent extends React.Component {
  render() {
    const { type, label = "", state, datapath = [] } = this.props;
    const data = datapath.map((path) => _.get(state, path, ''));
    return type === "grid" ? (
      <Grid.Column style={style}>
        <strong>{label}</strong> {data.join(", ")}
      </Grid.Column>
    ) : null;
  }
}

I think, when you are looping through the data and setting the state you are overriding the old data present in the state already.我认为,当您遍历数据并设置 state 时,您已经覆盖了 state 中存在的旧数据。

may be you will have to include the previous data as well as set new data in it something like this.可能你将不得不包括以前的数据以及在其中设置新数据,就像这样。

this.setState({data : [...this.state.data, data]})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何存储以前的值而不是将值存储在反应状态的对象数组中 - How can I store previous values instead of storing the value in array of objects in react state 为 flatlist 的所有项目创建单个 state 数组。 (反应原生) - Create a single state array for all items of flatlist. (React Native) 如何跟踪“Ant Design-Dynamic Form Item”并将所有值存储在单个对象状态中? - how can i keep track of "Ant Design- Dynamic Form Item" and store all values in a single object state? 我如何从表单提交的多个输入框中获取值并将这些值作为对象存储在React的状态数组中? - How can i get values from multiple input boxes on form submit and store the values as an object in an state array for React? 如何更新反应 state 中存在的字符串数组的第 0 个索引,保持所有其他索引值不受影响 - How to update 0th index of array of strings present in react state keeping all other index values unaffected 如何在映射 React 的状态下存储多个输入的值 - How to store a values of multiple inputs in the state of a mapping React 在React中将值添加到状态数组 - Adding values to a state array in React 反应状态数组添加值 - React state array adding values 如何将状态存储在本地存储中以作出反应? - How to store a state in localstorage for react? 如何通过 React 中的对象数组中单个道具的值数组 map? - How to map through an array of values of a single prop in an array of objects in React?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM