我的控制台中出现这样的错误:
Objects are not valid as a React child (found: object with keys {id, marketId, title, picture, language, flag, completed, date, rate, categories}). If you meant to render a collection of children, use an array instead.
这是我后面的数据:
const demoCompletedData = [
{
id: 1,
marketId: "1111-1111-1111-1111",
title: "Autonomous car",
picture: "https://th?id=OIP.fdvfdvfdvfdvfd&pid=Api",
language: "English",
flag: "🇬🇧",
completed: true,
date: "22/01/2019 10:30",
rate: 9.1,
categories: {
de: 1,
sp: 2,
uk: 0,
fr: 1,
us: 4,
},
},
我前面的代码使用 redux :
fetchDemo() {
this.props.demoFetchRequest();
const { marketId } = this.props.match.params;
axios.get(`/api/v1/passport-authenticate/market/${marketId}`)
.then((res) => { return res.data; })
.then(demo => this.props.demoFetchSuccess(demo))
.catch(error => this.props.demoFetchError(error));
}
我的渲染代码:
const { demo } = this.props;
以及我的代码作为返回:
{demo}
如何映射关键类别并读取其值(value)?
最佳答案
您的数据是一个对象数组。你不能像这样直接渲染它。 map在你的数组上并渲染你想要显示的内容。
{demo.map(el => (
<div>
<p>{el.id}</p>
<p>{el.title}</p>
{Object.keys(el.categories).map(key => (
<p>{key}:{el.categories[key]}</p>
))}
</div>
))}
const demo = [
{
id: 1,
marketId: "1111-1111-1111-1111",
title: "Autonomous car",
picture: "https://th?id=OIP.fdvfdvfdvfdvfd&pid=Api",
language: "English",
flag: "🇬🇧",
completed: true,
date: "22/01/2019 10:30",
rate: 9.1,
categories: {
de: 1,
sp: 2,
uk: 0,
fr: 1,
us: 4
}
}
];
const App = () => (
<div>
{demo.map(el => (
<div>
<p>{el.id}</p>
<p>{el.title}</p>
{Object.keys(el.categories).map(key => (
<p>
{key}:{el.categories[key]}
</p>
))}
</div>
))}
</div>
);
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"/>
关于javascript - 如何渲染对象数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55919784/