反应不渲染列表元素

时间:2018-12-22 18:09:13

标签: reactjs

问题

它没有显示item中的元素。目前没有任何显示。

List.js

import React from 'react';

const List = props => (
  <div>
    {
      props.items.map((item, index) => {
      return <div key={index}>
          <h1>{item.name}</h1>

          <p>{item.term}</p>

      </div>
    })}
  </div>
);

导出默认列表;

App.js

import React, {Component} from 'react'
import './App.css'
import List from './List';

class App extends Component {

    constructor(props) {
        super(props);

        this.state = {
            term: '',
            name: '',
            items: []
        };
    }

    onChange = (event) => {
        const { name, value } = event.target;
        this.setState({ [name]: value });

    }

    onSubmit = (event) => {
        event.preventDefault();

        this.setState({
            term: '',
            name: '',
            items: [
                ...this.state.items,
                this.state.term,
                this.state.name
            ]
        });

    }

    render() {
        const { term, name, items } = this.state;
        return (
          <div>
                <form className="App" onSubmit={this.onSubmit}>
                    <input name="term" value={this.state.term} onChange={this.onChange}/>
                    <input name="name" value={this.state.name} onChange={this.onChange}/>
                    <button>Submit</button>
                </form>


              <List items={this.state.items} />

            </div>
        );
    }

}

1 个答案:

答案 0 :(得分:1)

问题在onSubmit中,您需要转换为对象然后添加

onSubmit = event => {
    event.preventDefault();

    this.setState({
      term: "",
      name: "",
      items: [...this.state.items, { term: this.state.term, name: this.state.name}]
    });
    setTimeout(() => { console.log(this.state.items) }, 0)
  };

https://codesandbox.io/s/p7p128w7mx