从获取结果中的数组中获取值 (React.js)

Get value from array inside fetch result (React.js)

我需要访问 name 数组 area_set 中的 name 32=] 获取。我尝试了多种方法,但都是说 map is undefined 或其他。

这是 json 响应的图像:

这是我请求 json:

的代码
componentDidMount() {
    fetch(url + '/couch-model/1/', {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            'Authorization': 'JWT ' + (JSON.parse(localStorage.getItem('token')).token)
        }
    }).then(res => {
        if (res.ok) {
            return res.json();
        } else {
            throw Error(res.statusText);
        }
    }).then(json => {
        this.setState({
            model: json
        }, () => {
            console.log('model: ', json);
        });
    })
}

渲染方法中的代码如下:

 render() {

    const { model, isLoaded } = this.state;

    if (!isLoaded) {

        return (
            <div id="LoadText">
                Estamos a preparar o seu sofá!
            </div>
        )

    } else {

        return (
                    <div id="Esquerda">
                        <h2>
                            {model.area_set.map(area =>
                                model.area.area_set[0].name
                            )}
                        </h2>

                        <h1>{model.name}</h1>
                        <p>Highly durable full-grain leather which is soft and has  a natural look and feel.</p>

                        <h3>Design</h3>
                        <h4>Hexagon</h4>
                    </div>
        );

    }

}

我真的陷入了困境,有人可以帮忙吗?

getMeSomething = () => {
    if(this.state.model.area_set)
        return this.state.model.area_set.map(area => area.name)
}


render() {
    const { model, isLoaded } = this.state;
    if (!isLoaded) {
        return (
            <div id="LoadText">
                Estamos a preparar o seu sofá!
            </div>
        )
    } else {
        return (
                    <div id="Esquerda">
                        <h2>
                            {this.getMeSomething()}
                        </h2>
                        <h1>{model.name}</h1>
                        <p>Highly durable full-grain leather which is soft and has  a natural look and feel.</p>
                        <h3>Design</h3>
                        <h4>Hexagon</h4>
                    </div>
        );
    }
}

请试试这个方法。在您的情况下,状态中没有定义 area_set 因此很有可能找不到一些瞬间。所以它希望你处理那个错误

{model.area_set.map(area =>
    model.area.area_set[0].name
)}

这部分看起来很奇怪。试试这个:

{model.area_set.map(area =>
    area.name // This will yeild the name you are looking for once since the array is length = 1
)}