javascript - 在 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"));
解决方案
这样的事情可能会有所帮助。
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 });
推荐阅读
- python - Django 投票系统:以适当的方式确定排名
- c# - 桌面应用程序默认项目的 WinUI 3.0 给出运行时错误
- python - 在全局列表中存储新号码并每次添加更多
- html - 如何向 CSS 形状添加偏移轮廓?
- c# - Azure C# v2 函数:TableContinuationToken 不包含 ContinuationToken 的定义
- vue.js - 在用即将到来的数据列表Vuejs和vue-infinite-loading替换之前保留当前数据列表
- r - 试图找到纬度和经度坐标对之间的距离
- java - 在三个维度上检测三角形到三角形相交的最佳方法是什么?
- c++ - 如何在 C++ 中创建无限的动态对象
- javascript - AJAX - JS - 从 AJAX 响应创建表并放入