gpt4 book ai didi

javascript - 在 React.js 中运行 array 来获取texture_type

转载 作者:行者123 更新时间:2023-12-03 01:25:00 24 4
gpt4 key购买 nike

我仍然对ReactJs中的.map感到困惑,每次我尝试使用它时,我都会得到.map undefined。我需要遍历一个从 API 获取结果的数组,如下图所示:

Array(20)
0:
couch_model: 1
couchmodelextralayout_set: (4) [{…}, {…}, {…}, {…}]
created_on: "date"
dimensions_3D: "309cm D: 28.5cm H: 84cm"
dimensions_price: Array(3)
0:
arm: 28.5
dimensions: "331.5"
price_table_code: "table_1"
prices: Array(5)
0:
final_price: 0
texture_type: "Diamante"
1: {…},
2: {…},
3: {…},
4: {…}

基本上是这样的:

enter image description here

这是我的实际代码:

export class Material extends React.Component {

constructor(props) {
super(props);
this.state = {
isLoaded: false,
textures: {}
};
}

componentDidMount() {
const email = email;
const pass = pass;
const url = url;

/* Here is fetch to get token */

fetch(url + '/layout/?limit=20', {
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({
textures: json
}, () => {
console.log('textures: ', json);
});
})

}



render() {

const { isLoaded, textures } = this.state;


if (!isLoaded) {

return (
<div>{/*nothing*/}</div>
)

} else {

return (
<div>
{/*
This is where I want the texture to appear
*/}
</div>
);

}
}
}

基本上,我想以不同的 <p> 显示所有纹理标签,但我不知道如何访问数组...有什么建议吗?

最佳答案

如果您的获取结果(textures)实际上是一个数组,则 .map 函数应该可以正常工作。问题可能来自构造函数中 state.textures 的声明:您将其初始化为对象。通过执行此操作,组件的第一次渲染尝试在空对象上进行 .map。

尝试将其初始化为这样的数组

this.state = {
isLoaded: false,
textures: []
};

编辑:

在获取的最后一部分,您需要引用 json.results 而不是简单的 json,它是包含结果数组的对象

.then(json => {
this.setState({
textures: json.results
}, () => {
console.log('textures: ', json);
});
})

如果你想让整个对象保持在你的状态,

您可以像以前一样初始化状态:

this.state = {
isLoaded: false,
textures: {}
};

保持获取的最后一部分不变:

this.setState({
textures: json
}

并在渲染中映射这样的结果:

const { isLoaded, textures } = this.state;

return(
{
textures.results.map(result=>(
...
))
}
)

关于javascript - 在 React.js 中运行 array 来获取texture_type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51592211/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com