对于ReactJS我还是比较新的,并且通过伟大的SO社区的帮助,我一直在构建一个小练习,通过点击在两个组件之间来回移动项目。这些项目来自我硬编码到文件中的json数组items=[]
中的数据。我想知道如何从api获取数据,我已经阅读了文档,并知道我应该通过componentDidMount
方法来实现,但是我陷入了搞不清如何在方法中设置状态的问题。代码如下...reactjs - 从api获取数据
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')
);
谢谢!因此,这意味着我应该将'BoxOne:'的'this.state:'更改为一个空数组,因为我将在''props.items.map(item => item.id)'' componentDidMount()'方法现在吗? –
我认为你不应该直接在构造函数中获取boxOne(和Two),而是使用'componentWillMount()'而不是像getBox(num){/ *返回数字框* /}那样的函数' – pirs