我有一个旨在显示API中数据的组件:
class Item extends Component {
constructor(props) {
super(props);
this.state = {
output: []
}
}
componentDidMount() {
fetch('http://localhost:3005/products/157963')
.then(response => response.json())
.then(data => this.setState({ output: data }));
}
render() {
console.log(this.state.output);
return (
<ItemPanel>
<ItemBox>
<BoxTitle>{this.state.output}</BoxTitle>
</ItemPanel>
);
}
export default Item;
console.log(this.state.output)返回正确的数据,而我的组件无法渲染,但抛出此错误:
Objects are not valid as a React child (found: object with keys {id, general, brand, images}). If you meant to render a collection of children, use an array instead.
我猜来自api的数据是一个对象。我已经尝试使用JSON.parse或toString()了:/
答案 0 :(得分:1)
似乎您正在<BoxTitle>
中显示整个对象,让我们尝试在此处显示品牌。我已经更新了有问题的代码。
将初始状态output []
更新为{}
class Item extends Component {
constructor(props) {
super(props);
this.state = {
output: {}
}
}
componentDidMount() {
fetch('http://localhost:3005/products/157963')
.then(response => response.json())
.then(data => this.setState({ output: data }));
}
render() {
console.log(this.state.output);
const { brand = {name : ""} } = this.state.output // added default name until we get actual value
return (
<ItemPanel>
<ItemBox>
<BoxTitle>{brand.name}</BoxTitle>
</ItemPanel>
);
}
export default Item;
答案 1 :(得分:0)
当您的组件从API提取时,它会呈现render函数中描述的元素树。
output
的初始状态是一个空数组,这是一个好的开始。
从API加载数据或网络请求失败时,您应该考虑向应用程序用户显示什么。
我非常确定您不希望按原样呈现成功调用API后返回的对象。
也就是说,JSON.stringify
函数可用于在成功调用API之前查看在状态中设置的结果,然后选择要显示的字段,显示的方式和位置。
答案 2 :(得分:0)
您可以更好地使用条件渲染,
render() {
console.log(this.state.output);
return (
<ItemPanel>
<ItemBox>
{
if(this.state.output.brand.name !=== null) ?
<BoxTitle>{this.state.output.brand.name}</BoxTitle> :
<BoxTitle>Brand Name is Empty</BoxTitle>
}
</ItemPanel>
);
}