我正在學習反應。我在我的代碼中遇到以下問題:如何進一步改進此代碼以遵循標準?
在函數addCard中,爲什麼我需要調用setState?如果我不打電話setState卡沒有添加。
我已經讀過,突變狀態不好反應。所以應該使用像immutable.js這樣的庫。我想要知道這段代碼是否遵循React的標準實踐(無需深入研究redux)。
import React, {Component} from 'react';
import ReactDom from 'react-dom';
class App extends React.Component{
constructor(){
super();
this.state = {
name: '',
desc:'',
data : [
{
name: 'Batman',
desc:'I\'m Batman'
},
{
name: 'Superman',
desc: 'Up up and away'
},
{
name: 'Spiderman',
desc: 'Your friendly neighbour'
}
]
}
this.updateStateName =this.updateStateName.bind(this);
this.updateStateDesc =this.updateStateDesc.bind(this);
this.addCard =this.addCard.bind(this);
}
updateStateName(e) {
this.setState({name: e.target.value});
}
updateStateDesc(e) {
this.setState({desc: e.target.value});
}
addCard(){
this.state.data.push({
name: this.state.name,
desc: this.state.desc
})
let cards = this.state.data;
this.setState({
data: cards,name: '',desc: ''});
}
render(){
return(
<div>
<h3>Simple Form</h3>
<Form name={this.state.name}
desc={this.state.desc}
updateStatePropName={this.updateStateName}
updateStatePropDesc={this.updateStateDesc}
addCard={this.addCard}/>
<hr/>
<Content_Card data={this.state.data}/>
</div>
);
}
}
class Form extends React.Component{
constructor(props){
super(props);
}
render(){
return(
<div>
<input type="text" placeholder="Enter Title" value={this.props.name} onChange={this.props.updateStatePropName}/>
<br/>
<input type="text" placeholder="Enter Desc" value={this.props.desc} onChange={this.props.updateStatePropDesc} className="desc-box"/>
<br/>
<button type="button" onClick={() => this.props.addCard()}> Add New Card </button>
</div>
);
}
}
const Content_Card = (props) => {
return(
<div>
<Card listData = {props.data}/>
</div>
)
}
const Card = (props) =>{
const card = props.listData.map((item) => {
return <li className="content-card" key={item.name}>
<h4>{item.name}</h4>
<div>{item.desc}</div>
</li>
});
return(
<div>
<ul>{card}</ul>
</div>
)
}
ReactDom.render(<App/>, document.getElementById('app'))