我有一個Express API,在安裝reactJS組件時請求來自MongoDB的數據。通過Express API的響應使用ReactJS到.map通過響應的快速API
app.get('/api/characters', function(req, res) {
var db = req.db;
var collection = db.get('usercollection');
collection.find({},{},function(e,docs){
res.send({
data: docs
});
});
});
代碼字符組成:
export default class Characters extends React.Component {
constructor(props) {
super(props);
this.state = CharactersStore.getState();
this.onChange = this.onChange.bind(this);
}
componentDidMount() {
CharactersStore.listen(this.onChange);
CharactersActions.getCharacters('http://localhost:3000/api/characters');
}
componentWillUnmount() {
CharactersStore.unlisten(this.onChange);
}
onChange(state) {
this.setState(state);
}
render() {
return (
<section>
<div className="container">
<div className="row">
<h2 className="text-center">{this.props.route.header}</h2>
<hr className="star-light"/>
<CharacterList data={this.state.characters}/>
</div>
</div>
</section>
)
}
}
代碼字符組成行動
class CharactersActions {
constructor() {
this.generateActions(
'getCharactersSuccess',
'getCharactersFail'
);
}
getCharacters(query) {
requestPromise(query)
.then((res) => {
this.actions.getCharactersSuccess(res)
}).catch((err) => {
console.log('error:', err);
this.actions.getCharactersFail(err)
})
}
}
export default alt.createActions(CharactersActions);
代碼字符組成商店
class CharactersStore {
constructor() {
this.bindActions(CharactersActions);
this.characters = [''];
this.isLoading = true;
}
getCharactersSuccess(res) {
this.characters = res;
this.isLoading = false;
}
getCharactersFail(err) {
toastr.error(err.responseJSON && err.responseJSON.message || err.responseText || err.statusText);
}
}
export default alt.createStore(CharactersStore);
上面的字符組件在安裝時請求API並將響應數據一起發送到存儲以保存到狀態。
我再通過人物狀態進入子組件CharacterList道具(名爲數據)
人物名單組件
export default class CharacterList extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div className="col-lg-3 col-sm-6">
{console.log(this.props.data)}
// THIS IS WHERE I AM TRYING TO .MAP THROUGH THE RESULTS
</div>
)
}
}
我試圖使用.MAP循環通過返回的數據,但有點不確定如何進行,任何意見將不勝感激。被返回的數據如下:
{
"data": [
{
"_id": "58d5044b0898f816066227f1",
"character": "Luke Skywalker"
},
{
"_id": "58d504c60898f816066227f2",
"character": "Obi Wan Kenobi"
},
{
"_id": "58d504c60898f816066227f3",
"character": "Han Solo"
}
]
}
嗯,這是我認爲我需要,是位由最初的困惑'data'數組在我的結果中。我嘗試過使用你的代碼,但我得到this.props.data.map不是一個函數 – James
這是因爲,this.props.data沒有在初始渲染時定義。 – Ved
我更新了我的答案。基本上我加了檢查。 – Ved