首页 > 解决方案 > 如何映射(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'));
}

标签: javascriptphpreactjslaravel

解决方案


此错误是因为您正在异步获取数据,但是当组件被渲染时,数据尚未准备好,因此您可以有一个标志来显示数据正在获取,并且该标志何时为您想要的 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>)}

推荐阅读