您的位置:首页 > Web前端 > React

react js 遍历对象_遍历React.js中的嵌套对象

2020-08-20 15:55 393 查看 https://blog.csdn.net/cumian81

react js 遍历对象

If you've ever worked with APIs, you'll know that the structure of the data they return can get complicated quickly.

如果您曾经使用过API,就会知道它们返回的数据结构会很快变得复杂。

Imagine you call an API from your React project and the response looks something like this:

想象一下,您从React项目中调用一个API,响应看起来像这样:

Object1 {
Object2 {
propertyIWantToAcess:
anotherpropertyIWantToAcess:
}
}

You've stored the data within your component's state as

this.state.myPosts
, and can access the elements of the outer object with the following:

您已经将数据存储为

this.state.myPosts
作为组件状态内的数据,并且可以使用以下命令访问外部对象的元素:

render() {
console.log(this.state.myPosts);

const data = this.state.myPosts;

const display = Object.keys(data).map((d, key) => {
return (
<div className="my-posts">
<li key={key}>
{data.current_route}
</li>
</div>
);
});

return(
<div>
<ul>
{ display }
</ul>
</div>
);
}

But the problem is that you aren't able to access any of the inner objects.

但是问题是您无法访问任何内部对象。

The values of the inner objects will always change, so you aren't able to hardcode their keys and iterate through those to get the proper values.

内部对象的值将始终更改,因此您无法对它们的键进行硬编码并对其进行迭代以获取正确的值。

可能的解决方案 (Possible solutions)

It can be difficult to work directly with complex API responses, so let's take a step back and simplify:

直接处理复杂的API响应可能很困难,因此让我们退后一步并简化一下:

const visit = (obj, fn) => {
const values = Object.values(obj)

values.forEach(val =>
val && typeof val === "object" ? visit(val, fn) : fn(val))
}

// Quick test
const print = (val) => console.log(val)

const person = {
name: {
first: "John",
last: "Doe"
},
age: 15,
secret: {
secret2: {
secret3: {
val: "I ate your cookie"
}
}
}
}

visit(person, print)
/* Output
John
Doe
15
I ate your cookie
*/

The

lodash
library has simple methods to accomplish the same thing, but this is a quick and dirty way to do the same thing in vanilla JS.

lodash
库具有完成相同任务的简单方法,但这是在香草JS中完成相同任务的快速而肮脏的方法。

But say you want to simplify further, something like:

但是说您想进一步简化,例如:

render() {
// Logs data
console.log(this.state.myPosts);

const data = this.state.myPosts;

// Stores nested object I want to access in posts variable
const posts = data.content;

// Successfully logs nested object I want to access
console.log(posts);

// Error, this will not allow me to pass posts variable to Object.keys
const display = Object.keys(posts).map(key =>
<option value={key}>{posts[key]}</option>
)

return(
<div>
{display}
</div>
);
}

But you get an error,

TypeError: can't convert undefined to object error
whenever you try to pass
posts
to
Object.keys
.

但是,您遇到一个错误,

TypeError: can't convert undefined to object error
每当尝试将
posts
传递给
Object.keys
时,
TypeError: can't convert undefined to object error

Keep in mind that this error has nothing to do with React. It's illegal to pass an object as a child of a component.

请记住,此错误与React无关。 将对象作为组件的子代传递是非法的。

Object.keys()
only returns the keys of the object that's passed in as a parameter. You'll need to call it multiple times to iterate through all the nested keys.

Object.keys()
仅返回作为参数传入的对象的键。 您需要多次调用它以遍历所有嵌套键。

If you need to display the whole nested object, one option is to use a function to convert each object into a React component and pass it as an array:

如果需要显示整个嵌套对象,一种选择是使用函数将每个对象转换为React组件并将其作为数组传递:

let data= []

visit(obj, (val) => {
data.push(<p>{val}</p>)  // wraps any non-object type inside <p>
})
...
return <SomeComponent> {data} </SomeComponent>

有用的包裹 (Useful packages)

Another option is to use a package like json-query to help iterate through the nested JSON data.

另一个选择是使用json-query之类的包来帮助迭代嵌套的JSON数据。

Here's a modified version of the

render
function above using
json-query
:

这是上面使用

json-query
render
函数的修改版本:

render() {
const utopian = Object.keys(this.state.utopianCash);
console.log(this.state.utopianCash);

var author = jsonQuery('[*][author]', { data: this.state.utopianCash }).value
var title = jsonQuery('[*][title]', { data: this.state.utopianCash }).value
var payout = jsonQuery('[*][total_payout_value]', { data: this.state.utopianCash }).value
var postLink = jsonQuery('[*]

翻译自: [url=https://www.freecodecamp.org/news/iterate-through-nested-object-in-react-js/]https://www.freecodecamp.org/news/iterate-through-nested-object-in-react-js/" target=_blank>', { data: this.state.utopianCash }).value var pendingPayout = jsonQuery('[*][pending_payout_value]', { data: this.state.utopianCash }).value var netVotes = jsonQuery('[*][net_votes]', { data: this.state.utopianCash }).value let display = utopian.map((post, i) => { return ( <div className="utopian-items"> <p> <strong>Author: </strong> {author[i]} </p> <p> <strong>Title: </strong> <a href={`https://www.steemit.com` + postLink[i]}>{title[i]}</a> </p> <p> <strong>Pending Payout: </strong> {pendingPayout[i]} </p> <p> <strong>Votes: </strong> {netVotes[i]} </p> </div> ); }); return ( <div className="utopian-container"> {display} <User /> </div> ); } }[/code]

翻译自: [url=https://www.freecodecamp.org/news/iterate-through-nested-object-in-react-js/]https://www.freecodecamp.org/news/iterate-through-nested-object-in-react-js/

react js 遍历对象

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: