javascript - 如何从状态内更新对象内的数组?

标签 javascript reactjs

需要一些帮助...我如何更新状态以反射(reflect)添加到特定 child 的新计划(按 ID)?

我目前有一个提供一组新数据的表单,如下所示(表单中的值在空字符串中):

{
  date: '',
  parent: '',
  activity: ''
}

我在下面创建了这个函数,我将 child 的 id 和看起来像上面那个的新时间表传递给它......我被困在这个上:

addSched = (id, schedule) => {
  const newSched = this.state.children.map(child => {
    if (child.id !== id) return child;
    return {
      ...child,
      schedules: schedule
    };
  });
  this.setState({ children: newSched });
};

我现在的状态是这样的:

state = {
  children: [
  {
    id: 1,
    firstName: 'Bella',
    lastName: 'Laupama',
    schedules: [
      {
        id: 1,
        date: '25 December 2018',
        parent: 'Chris',
        activity: 'Christmas'
      },
      {
        id: 2,
        date: '31 December 2018',
        parent: 'Laura',
        activity: 'New Years Eve'
      }
    ]
  },
  {
    id: 2,
    firstName: 'Cara',
    lastName: 'Malane',
    schedules: [
      {
        id: 1,
        date: '25 December 2018',
        parent: 'Chris',
        activity: 'Christmas'
      } ...etc

具有表单的组件具有以下内容:

export default class AddSched extends React.Component {
  state = {
   date: '',
   parent: '',
   activity: ''
  }

handleChange = e => {
  this.setState({
   [e.target.name]: e.target.value
  })
 }

submitHandler = e => {
  e.preventDefault()
  this.props.addSched(this.props.id, this.state)
  console.log('SUBMITTED:', this.state)
    this.setState({
    date: '',
    parent: '',
    activity: ''
    })
}

最佳答案

您可以使用数组展开运算符连接现有数组和新计划:

schedules: [...child.schedules, schedule]

这里是完整的功能变化:

ddSched = (id, schedule) => {
  const newSched = this.state.children.map(child => {
    if (child.id !== id) return child;
    return {
      ...child,
      schedules: [...child.schedules, schedule]
    };
  });
  this.setState({ children: newSched });
};

关于javascript - 如何从状态内更新对象内的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53389221/

相关文章:

javascript - [类型错误 : Cannot read property 'GlobalWorkerOptions' of undefined]

reactjs - ESLint - 强制 PropTypes

javascript - 类型 '() => Promise<AxiosResponse<any>>'不能用作索引类型[ReactJs]

javascript - AngularJS 使用控制台更改变量

javascript - 调整旧的 Javascript/jQuery 代码以使用不同的 JSON 格式

javascript - 未声明无法读取未定义的属性 'setState'

reactjs - 在 "storybook js"中提供静态文件

css - 我想删除 Bootstrap 链接中的下划线

javascript - Firebase 函数 Express : How to get URL params with paths

javascript - 当 parent 监听点击事件时,复选框在 ngTemplateOutlet 中不起作用 - 错误?