首页 > 解决方案 > 在 React 中处理复杂的数据结构

问题描述

我是 React 的新手,我想知道是否有人可以帮助我。我有一个像 slack 这样的应用程序,我可以在其中添加一个新团队并添加一个频道。问题是这是一个复杂的 DS,我一直在尝试使用通过输入传递的新数据来修改状态,无论是在团队还是渠道中,但我没有成功

import React, { Component } from "react";
import { render } from "react-dom";
import "./style.css";

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      newTeamValue: "",
      teams: [
        {
          newChannel: "",
          name: "Team1",
          channels: [ 
            {
              name: "Channel1",
              index: 1
            },
            {
              name: "Channel2",
              index: 2
            }
          ]
        }
      ]
    };
    this.addTeam = this.addTeam.bind(this)

    this.addChannel = this.addChannel.bind(this)
  }

  addTeam(e) {
    e.preventDefault();
    this.setState(prevState => ({
      newTeam: "",
      teams: [
        ...prevState.teams,
        {
          name: this.state.newTeam,
          channels: []
        }
      ]
    }));
  }

  addChannel(e){
    e.preventDefault()
    this.setState(prevState => ({
      newChannel:"",
      teams: [
        ...prevState.teams,
        {
          channels: [...prevState, {
            name: this.state.teams.newChannel
          }]
        }
      ]
    }))
  }

  render() {
    return (
      <div>
        <ul>
          {this.state.teams.map(team => {
            return (
              <div>
                <li>{team.name}</li>
                <input onChange={e => this.setState({ newChannel: e.target.value })} value={this.state.newChannel} />
                <button onClick={this.addChannel}>Add New Channel</button>
                <ul>
                  {team.channels.map(channel => {
                    return (
                      <div>
                        <h2>{channel.name}</h2>
                      </div>
                    );
                  })}
                </ul>
              </div>
            );
          })}
        </ul>
        <input onChange={e => this.setState({ newTeam: e.target.value })} value={this.state.newTeam} />
        <button onClick={this.addTeam}>Add new Team</button>
      </div>
    );
  }
}

render(<App />, document.getElementById("root"));

标签: javascriptreactjs

解决方案


这样的事情可能会有所帮助。

const newTeams = [...this.state.teams, { name: "Team3", channels: [] }]
this.setState({ teams: newTeams });

newTeams是一个数组,它包含所有现有团队 ( ...this.state.teams),以及一个名为 的附加团队Team3

有些库(例如immutablejs)可能对您有用。我个人不经常使用它们,所以我无法为您提供示例,但可能值得关注。

编辑:您提到您是 React 的新手,不确定您是否也是 JS 的新手。如果您以前没有见过...,那就是Spread 运算符

Edit2:关于向现有团队添加频道的评论

const newTeams = [
    ...this.state.teams,
    {
        name: "Team123",
        channels: [
            ...this.state.Team123.channels,
            { name: "NewChannel", index: 123 }
        ]
    }
];

this.setState({ team: newTeams });

推荐阅读