對於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