【发布时间】:2018-09-05 06:08:53
【问题描述】:
我是 React Js With Laravel Php Framework 的新手。
问题: 是否可以将每个数组对象获取到我的 API 并在每个部分中获取它。因为我的控制台中出现错误提示
未捕获的类型错误:this.state.missions.map 不是函数。我不知道问题是什么,但主要目标是获取每个对象,并且循环必须在视图中的特定 div 部分中
例如。如果我已经得到了任务的数组对象并存储了
<div className="mission">
the object of mission must be here.
</div>
<div className="store">
the object of store must be here.
</div>
和其他对象。等等
我的控制者:
public function index() {
$content_mission = DB::table('content_structure')
->where('content_pages','=','Home')
->where('content_section','=','Mission-Vision')
->where('status','=','Active')
->orderBy('content_id','Desc')
->limit(1)
->get();
$content_store = DB::table('content_structure')
->leftJoin('content_upload_assets','content_structure.content_id','=','content_upload_assets.cid')
->where('content_pages','=','Home')
->where('content_section','=','Store')
->where('status','=','Active')
->orderBy('content_id','Desc')
->limit(1)
->get();
return response()->json(
array(
'mission'=>$content_mission,
'store'=>$content_store)
);
}
我的组件:
export default class Content extends Component {
constructor() {
super();
this.state = {
missions: [],
store: [],
}
}
componentWillMount() {
axios.get('/api/contents').then(response => {
this.setState({
missions: response.data
});
}).catch(error => {
console.log(error);
})
}
render() {
return (
<div>
// this div is for mission
<div className="mission-section">
<h1></h1>
<p></p>
<div className="container">
{this.state.missions.map(mission => <li>{mission.content}</li>)}
</div>
</div>
//this div is for store
<div className="Store"></div>
</div>
)
}
}
if(document.getElementById('app'))
{
ReactDOM.render(<Content/>, document.getElementById('app'));
}
【问题讨论】:
-
您指出的错误明确指出
this.state.missions不是数组或typeof 数组。 -
如何解决?
-
您似乎从 API 响应中返回了一个对象。你可以试试
response.data.missions吗? -
您在 Api 调用完成之前获取该状态
missions属性。另外我不确定 response.data 是一个数组。错误的主要原因:response.data不能是 typeof 数组。 -
@Alserda 同样的错误
标签: javascript php reactjs laravel