我有JSON数据" data .js"并在App.js"在初始化状态
在"updateList"应用程序"我正在获取"数据"。-源自"insert ";Form.js"我需要调用setstate;updatellist "的"App.js".
请帮我更正一下我的"Form.js"方法;和";updateList"app.js"方法
App.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>
)
}
}
Items.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 ;
Form.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 ;
Data.js
export const list = [
{
title: "I",
details: "ONE",
},
{
title: "II",
details: "TWO",
},
{
title: "III",
details: "THREE",
},
];
谢谢
您需要传递带有键"title"one_answers";details"。不是input1
和input2
。那么就像这样在Form:
const newItem = {
title: this.state.input1,
details: this.state.input2,
}
this.props.onsubmit(newItem);
终于有答案了!
updateList(dataa){
this.setState(ps=>(
{ listState: [
dataa,
...ps.listState
]}
)
)
}
"updateList"在"App.js"中,这行得通