简体   繁体   English

创建一个具有键值数组的空状态对象,该键值数组以JSON对象作为值,然后更改这些json对象

[英]creating an empty state object that has a key value array with JSON objects as the values and than changing those json objects

I am attempting to create a reactJS state that has an empty array in it on construction. 我正在尝试创建一个在构造上具有空数组的reactJS状态。 Once i receive a message, that is a JSON object, I would want to create a key in that array and store that received message as the value under that key. 收到一条消息(即JSON对象)后,我想在该数组中创建一个键,并将接收到的消息存储为该键下的值。

for example. 例如。 I have 我有

array x =[] 数组x = []

JSON_obj = {"data":"mydata"} JSON_obj = {“数据”:“ mydata”}

in normal javascript I could say 用普通的javascript我可以说

x["some_key"] = JSON_obj x [“ some_key”] = JSON_obj

I am attempting accomplish this in reactJS inside the state. 我试图在状态内的reactJS中完成此操作。

 class App extends Component { constructor(props) { super(props); this.state = { cusipData: [] }; this.socket = io("adresss"); this.socket.on("ringBuffer", function(data) { addMessage(JSON.parse(data)); }); const addMessage = data => { this.setState({ cusipData: this.state.cusipData[data.cusip], data }); console.log("this.state"); console.log(this.state); }; } } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> 

I would be careful with using setState when self-referencing this.state in the method as state should remain immutable. 在方法中自引用this.state时,我会谨慎使用setState ,因为state应该保持不变。 This should work. 这应该工作。

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      cusipData: []
    };

    this.socket = io("adresss");

    this.socket.on("ringBuffer", function(data) {
      addMessage(JSON.parse(data));
    });

    const addMessage = data => {
      this.setState((prevState, props) => {
        const newCusipData = prevState.cusipData;
        newCusipData[data.cusip] = data;

        return {
          cusipData: newCusipData
        };
      });

      console.log("this.state");
      console.log(this.state);
    };
  }
}

The following method addMessage adds the data.cusip parameter to the existing state.cusipData array. 下面的方法addMessage添加data.cusip参数到现有state.cusipData阵列。

 class App extends Component { constructor(props) { super(props) this.state = { cusipData: [], }; this.socket = io("adresss") this.socket.on('ringBuffer', function(data){ addMessage(JSON.parse(data)); }); const addMessage = data => { // adds the new data.cusip to the existing state array this.setState({ cusipData: [...this.state.cusipData, data.cusip] }); }; } 

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM