0

我在“Data.js”中有 JSON 数据,在“App.js”中它被初始化为状态。

在“App.js”的“updateList”方法中,我得到“dataa”——来自“Form.js”的“insertIt”,我也需要在“App.js”的“updateList”中“setstate”。

请帮我纠正“Form.js”的“insertIt”方法和“app.js”的“updateList”方法

应用程序.js

 import { Component } from 'react';
import Items from './Items';
import { list } from './data';
import Form from './form';
class App extends Component {
  constructor(props){
    super(props);
    this.state = {
      listState : list
    }
    this.updateList = this.updateList.bind(this);
  }
  updateList(dataa){
    this.setState(ps=>({
      listState: [
        ...ps.listState,   //  HELP ME FIX THIS PART
        dataa
      ]
    }));
    return dataa;
  }
  render() {
    return (
      <div>
        <Items listofitems={this.state.listState}></Items>
        <Form onsubmit={this.updateList}></Form>
      </div>
    )
  }
}

项目.js

 import React, { Component } from "react";
class Items extends Component{
    render() {
        return(
           <div>
               {this.props.listofitems.map(i=> (
        <center>
            <h2>{i.title}</h2>
            <p>{i.details}</p>
        </center>
    ))}
            </div>
        )
    }
}
export default Items ;

表单.js

import React, { Component } from "react";
class Form extends Component{
    constructor(props){
        super(props);
        this.state={
            input1: '',
            input2: ''
        }
        this.insertIt = this.insertIt.bind(this);
        this.handler1 = this.handler1.bind(this);
        this.handler2 = this.handler2.bind(this);
    }
    handler1(e1){ this.setState({input1: e1.target.value});   }
    handler2(e2){ this.setState({input2: e2.target.value});   }
    insertIt(e){
        e.preventDefault();
        const newItem =
            {
                input1: this.state.input1,
                input2: this.state.input2,
            }
            this.props.onsubmit(newItem);
    }
    render() {
        return(
          <form onSubmit={this.insertIt}>
              <label>Enter both</label>
              <input type="text" value={this.state.input1} placeholder="in roman" onChange={this.handler1}></input>
              <input type="text" value={this.state.input2} placeholder="# in words" onChange={this.handler2}></input>
              <button type="submit">Insert</button>
          </form>
        )
    }
}
export default Form ;

数据.js

export const list = [
    {
      title: "I",
      details: "ONE",
    },
    {
        title: "II",
        details: "TWO",
      },
      {
        title: "III",
        details: "THREE",
      },
  ];

谢谢

4

2 回答 2

0

您需要传递带有“标题”和“详细信息”键的对象。不是input1input2。因此,只需在 Form 中像这样更新:

const newItem = {
    title: this.state.input1,
    details: this.state.input2,
}
this.props.onsubmit(newItem);
于 2021-08-18T13:29:34.550 回答
0

终于得到答案了!

updateList(dataa){
    this.setState(ps=>(
      { listState: [
        dataa,
        ...ps.listState 
      ]}
      )
    )
  }

“App.js”中的“updateList”,这有效

于 2021-08-20T07:10:16.800 回答