我想使用AddItem将项目添加到另一个组件的列表中。但是,我一直在获取undefined

如何将项目正确添加到列表?

我也将其放在CodeSandbox中:https://codesandbox.io/s/Mjjrm3zrO

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      movies: [x.movies],
    };
  }
  render() {
    return (
      <div>
        <CreateNew addItem={item => this.setState({ movie: [item].concat(this.state.movie) })} />
          {x.movies.map(movie => (
            <Result key={movie.id} result={movie} addItem={item => this.setState({ genres: [item].concat(this.state.genres) })} />
          ))}
      </div>
    );
  }
}

class CreateNew extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: '',
      genres: '',
    };
  }
  handleSubmit1 = (e, value) => {
    e.preventDefault();
    this.props.addItem(this.state.value)
    console.log(this.props.item);
  };
  onChange = e => {
    this.setState({ value: {'name': e.target.value}, genres: [{ name: 'Test', type: 1 }, { name: 'Foo', type: 10 }] });
    console.log(this.state.value);
  };
  render() {
    const { value, genres } = this.props;
    return (
      <form onSubmit={this.handleSubmit1}>
        Add a new movie
        <input onChange={this.onChange} type="text" />
        <button type="submit">Save</button>
      </form>
    );
  }
}

class Result extends React.Component {
  render() {
    const { result } = this.props;

    return (
      <div>
        <li>
          {result.name} {' '}
          ({result.genres.map(x => x.name).join(', ')}){' '}
        </li>

      </div>
    );
  }
}

最佳答案

变化:

1.而不是仅从子组件发送名称,而是发送将包含名称和类型的整个状态变量。

handleSubmit1 = (e, value) => {
    e.preventDefault();
    this.props.addItem(this.state)
};


2.您正在将初始值电影从json存储到状态变量,因此请使用该状态变量创建ui,因为一旦添加任何新项,您将更新状态变量,因此,如果您使用初始json创建ui,则使用新项不会反映在ui中。

{this.state.movies.map(movie => (
    <Result key={movie.id} result={movie} />
))}


3.像这样更新state可变影片:

<CreateNew addItem={item => this.setState({ movies: [{name: item.value.name, genres: item.genres}].concat(this.state.movies) })} />


检查工作解决方案:https://codesandbox.io/s/3nD0RgRp

10-04 22:17