【发布时间】:2017-07-03 01:01:24
【问题描述】:
我对 ReactJS 还很陌生,在伟大的 SO 社区的帮助下,我一直在构建一个小练习,通过单击在两个组件之间来回移动项目。这些项目来自我硬编码到文件中的 json 数组 items=[] 中的数据。我想知道如何从 api 获取数据,我已经阅读了文档并且知道我应该通过 componentDidMount 方法来做到这一点,但是我在弄清楚如何在方法中设置状态时遇到了困难。代码如下...
class SingleItem extends React.Component {
render() {
let data = this.props.data;
return (
<li onClick={this.props.onClick}>
<div> {data.name} </div>
</li>
);
}
}
class ItemList extends React.Component {
render() {
let itemArr = this.props.allItems;
let myItems = this.props.items;
let handleEvent = this.props.handleEvent;
let listItems = itemArr.map((itemObj) => {
if (!myItems.includes(itemObj.id)) return null;
return <SingleItem
key={itemObj.id}
data={itemObj}
onClick={() => handleEvent(itemObj.id)}
/>;
});
return (
<ul>
{listItems}
</ul>
);
}
}
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [],
boxOne: props.items.map(item => item.id), // init the boxes with
itemIds
boxTwo: []
};
this.handleEvent = this.handleEvent.bind(this);
}
handleEvent(itemId) {
const isInBoxOne = this.state.boxOne.includes(itemId);
// Heres the magic, if the item is in the first Box, filter it out,
// and put into the second, otherwise the other way around..
this.setState({
boxOne: isInBoxOne
? this.state.boxOne.filter(i => i !== itemId)
: [ ...this.state.boxOne, itemId ],
boxTwo: isInBoxOne
? [ ...this.state.boxTwo, itemId ]
: this.state.boxTwo.filter(i => i !== itemId)
});
}
render() {
return (
<div className="wrapper">
<div className="box">
<ItemList handleEvent={this.handleEvent} items={this.state.boxOne} allItems={this.props.items} />
</div>
<div className="box">
<ItemList handleEvent={this.handleEvent} items={this.state.boxTwo} allItems={this.props.items} />
</div>
</div>
);
}
};
var items = [
{name: "Item 1", id: 1},
{name: "Item 2", id: 2},
{name: "Item 3", id: 3},
{name: "Item 4", id: 4},
{name: "Item 5", id: 5},
{name: "Item 6", id: 6}
]
ReactDOM.render(
<App items={items} />,
document.getElementById('root')
);
【问题讨论】:
标签: javascript reactjs