简体   繁体   English

如何从状态中拉出特定对象并获取其中一个项目?

[英]How can I pull a specific object from the state and get one of its items?

I have the following component named Tweets.js:我有以下名为 Tweets.js 的组件:

import React, {Component} from "react";

export default class Tweets extends Component {
    constructor(props) {
        super(props);
        this.state = {tweets: [], users: []}; 
    }

    componentDidMount() {
        this.TweetList();
        this.UserList();
    }

    TweetList() {
        fetch('http://***.***.***.***:****/api/posts')
            .then(res => res.json())
            .then((data) => {
                this.setState({ tweets: data })
            })
            .catch(console.log);
    }

    UserList() {
        fetch('http://***.***.***.***:****/api/users')
            .then(res => res.json())
            .then((data) => {
                this.setState({ users: data })
            })
            .catch(console.log);
    }

    render() {
        const tweets = this.state.tweets.map((item, i) => (
            <div>
                <div class="tweet_box">
                    <p>{item.tweet}</p>
                </div>
            </div>
        ));

        const users  = this.state.users.map((item, i) => (
            <div>
                <h2>{item.twitterhandle}</h2>
            </div>
       ))

        return (
            <div className="tweet">{ tweets }</div>
        )
    }
}

users json:用户json:

[
 {
    "userid": 337282,
    "twitterhandle": "sean",
    "email": "sean@sean.com"
  },
  {
    "userid": 1234563,
    "twitterhandle": "DidItWork",
    "email": "pleasework@work.com"
  },
  {
    "userid": 3728,
    "twitterhandle": "Isthisup",
    "email": "isthisup@up.com"
  },
  {
    "userid": 1234567,
    "twitterhandle": "blah",
    "email": "matt@knop.com"
  }
]

posts json:帖子json:

[
  {
    "postid": 2,
    "tweet": "Hello, World #2",
    "userid_id": 337282
  },
  {
    "postid": 4,
    "tweet": "Hello, World #1",
    "userid_id": 3728
  },
  {
    "postid": 1,
    "tweet": "Hello, World #4",
    "userid_id": 3728
  },
  {
    "postid": 3,
    "tweet": " Hello, World! How's it?",
    "userid_id": 1234563
  }
]

I am trying to return the list of Posts from the posts json file and I was able to accomplish that.我试图从帖子 json 文件中返回帖子列表,我能够做到这一点。 My question is, how am I able to take the userid_id number, find it in the users json file, pull the username, and display it inside the following code?我的问题是,我怎样才能获取 userid_id 号,在用户 json 文件中找到它,提取用户名,并在以下代码中显示它?

const tweets = this.state.tweets.map((item, i) =>   
    <div>
        <div class="tweet_box">
            <p>{item.tweet}</p>
        </div>
    </div>
));

All I have been able to accomplish is to get it to display a separate list of the users but I can't figure out how to route the data into the above code - in say, an h1 tag.我所能完成的就是让它显示一个单独的用户列表,但我无法弄清楚如何将数据路由到上面的代码中——比如说,一个 h1 标签。

I am very new to react and I apologize if my code is terrible.我对反应很陌生,如果我的代码很糟糕,我深表歉意。 I am open to any and all suggestions or reference I can look at.我愿意接受我可以查看的任何和所有建议或参考。 I looked through the React documentation and found the section on keys and it appeared to be the correct direction, but still couldn't figure it out.我查看了 React 文档,找到了关于键的部分,它似乎是正确的方向,但仍然无法弄清楚。

If there is anything I can add to clarify my issue, please don't hesitate to ask.如果我可以添加任何内容来澄清我的问题,请随时提出。

I appreciate all of your time.我很感激你所有的时间。

EDIT: I am attempting to work through the problem some more and added the following function:编辑:我正在尝试解决更多问题并添加以下功能:

GetUsername() {
    return this.state.users[1];
}

I then made the following changes to my render:然后我对渲染进行了以下更改:

const tweets = this.state.tweets.map((item, i) => (
    <div>
         <div class="tweet_box">
              <h1>{this.GetUsername()}</h1>
              <p>{item.tweet}</p>
         </div>
    </div>
));

I added我加了

<h1>{this.GetUsername()}</h1>

Which produced the following error:这产生了以下错误:

Error: Objects are not valid as a React child (found: object with keys {userid, twitterhandle, email, password}).错误:对象作为 React 子对象无效(找到:带有键 {userid、twitterhandle、email、password} 的对象)。 If you meant to render a collection of children, use an array instead.如果您打算渲染一组子项,请改用数组。

You are close.你很近。 React doesn't render objects directly but can render primitives, like strings and numbers. React 不直接渲染对象,但可以渲染基元,如字符串和数字。 this.state.users[1] will always return the second user object in the users array, which probably isn't what you want. this.state.users[1]将始终返回users数组中的第二个用户对象,这可能不是您想要的。

Update your utility to take an id and find the correct user object.更新您的实用程序以获取 id 并找到正确的用户对象。

getUserById = (id) => this.state.users.find(({ userid }) => userid === id);

Then call that in the render to get the user object and if found access the twitterhandle property.然后在渲染中调用它以获取用户对象,如果找到则访问twitterhandle属性。

const tweets = this.state.tweets.map((item, i) => (
    <div>
        <div class="tweet_box">
          <h1>{this.getUserById(item.userid_id)?.twitterhandle}</h1>
            <p>{item.tweet}</p>
        </div>
    </div>
));

编辑 how-can-i-pull-a-specific-object-from-the-state-and-get-one-of-its-items

This GetUserName method returns an object (the user's object).这个 GetUserName 方法返回一个对象(用户的对象)。 It cannot render an object, but it can render a string or a number.它不能渲染对象,但可以渲染字符串或数字。 for example:例如:

GetUsername() {
    return this.state.users[1].twitterhandle;
}

Also you can return a array and iterate with a map like you do in the const "tweet"您也可以返回一个数组并使用映射进行迭代,就像在 const“tweet”中所做的那样

The error you are getting, "Objects are not valid as a React child" , is because your GetUsername function actually returns the whole user object instead of just the username.您收到的错误是"Objects are not valid as a React child" ,是因为您的GetUsername函数实际上返回了整个用户对象,而不仅仅是用户名。 You need to change this.state.users[1] to this.state.users[1].twitterhandle .您需要将this.state.users[1]更改为this.state.users[1].twitterhandle

But we want to find the right user for each tweet, not just return the first user all the time.但是我们希望为每条推文找到合适的用户,而不是一直返回第一个用户。 We do this by looking through the users array and finding the element where user.userid matches tweet.userid_id .我们通过查看 users 数组并找到user.userid匹配tweet.userid_id的元素来做到这tweet.userid_id

Let's make a getUsername function that takes the numeric user id as an argument:让我们创建一个getUsername函数,它将数字用户 ID 作为参数:

getUsername( id ) {
    const user = this.state.users.find( user => user.id === id );
    if ( user ) {
       return user.twitterhandle;
    } else {
        return '';  // fallback to return an empty string if no user was found
    }
}

(You can write that a lot more concisely, but I wanted to be clear about the intention) (你可以写得更简洁,但我想弄清楚意图)

Now we can call that with the id from the tweet item现在我们可以使用推文项目中的 id 调用它

const tweets = this.state.tweets.map((item, i) => (
    <div>
         <div class="tweet_box">
              <h1>{this.getUsername(item.userid_id)}</h1>
              <p>{item.tweet}</p>
         </div>
    </div>
));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM