javascript - 如何映射(Laravel - ReactJS)中的每个数组对象
问题描述
我是 React Js With Laravel Php Framework 的新手。
问题: 是否可以将每个数组对象获取到我的 API 并在每个部分中获取它。因为我的控制台中出现错误提示
未捕获的 TypeError: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>
和其他对象。ETC
我的控制器:
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'));
}
解决方案
此错误是因为您正在异步获取数据,但是当组件被渲染时,数据尚未准备好,因此您可以有一个标志来显示数据正在获取,并且该标志何时为您想要的 flase 或 true。您可以通过 && 运算符呈现您的数据作为回报,如下所示:
{this.state.flag && this.state.missions.map(mission => <li>{mission.content}</li>)}
或者你可以很容易地说当有任何数据时渲染它
{&& this.state.missions this.state.missions.map(mission => <li>{mission.content}</li>)}
推荐阅读
- java - 如何从另一台计算机访问 WildFly 12 服务器上的 web 应用程序?
- sql - 如何将 n 个列名分配给单个变量?
- rabbitmq - RabbitMQ:在 AMQP 配置中禁用明文身份验证机制
- javascript - 三.JS 和 Firebase 托管 CORS 问题
- python - 从 python 脚本中执行 `pipenv` 命令
- javascript - 如何在 NodeJs 中自动删除所有超过一周的记录/行?
- c# - 如何处理 VSIX 中的键盘事件?
- css - npm 启动时出错 - 未定义变量:\node_modules\bootstrap\scss\mixins\_grid-framework.scss 中的“$grid-row-columns”(第 37 行,第 30 列)
- python - Python:为什么我在调用 geospark 时会出错?
- c# - 如何在启动时执行 .NET Core 控制台应用程序作为树莓派的(守护程序)服务