React - 在状态下写入和读取嵌套对象

React - write and read nested objects in state

我正在开发一个 React 应用程序,它从 Google 的 Firebase 上的数据库中获取数据。

数据库是这样组织的:

users {
    user 1 {
        name
        surname
        ... 
    }
    user 2 {
        name
        surname
        ...
    }
}

我如何在 React 中检索数据:

我从 url 中获取位置和工具来过滤搜索结果(现在只使用位置,但想同时使用两者),并且我成功地设法将对象打印在控制台。

componentWillMount(){
    const searchResults = FBAppDB.ref('users');

    let location = this.props.location;
    let instrument = this.props.instrument;

    let profiles = [];
    searchResults.orderByChild('location').equalTo(location).on('value', (snap) => {
        let users = snap.val();
        Object.keys(users).map((key) => {
            let user = users[key];
            console.log(user);
            profiles.push(user);
        });
    });

    // this.setState({users: profiles[0]});
}

对象的控制台输出:

Object {name: "Whatever", surname: "Surrname", ... }

我似乎没有做的是将这些对象(可能不止一个)保存在状态中,因此当用户更改页面上的其他过滤器时我可以更新视图。

我尝试对实际用户进行 setState,但状态结果为空,知道吗?

除了写入之外,从状态中获取数据的最佳方式是什么?如何循环遍历状态中的对象?

谢谢

编辑

这是我的渲染函数的样子:

render(){
    return(
        <Row>
            {
                Object.keys(this.state.users).map(function (key) {
                    var user = this.state.users[key];
                    return <SearchResult user={user} />
                })
            }
        </Row>
    );
}

我试过直接打印this.state.users,但是不行。因此,我试图提出一个(无效的)解决方案。对于任何菜鸟错误,我深表歉意。

尝试将 setState 放在 Object.keys(...) 之后的 .on(() => ...) 中。这是对服务器的异步调用,对吧?我想 setState 是在调用服务器之后立即调用的,但在您检索任何数据之前。

I tried to setState the actual user but the state results empty, any idea?

是因为你的DB操作searchResult异步而JavaScript没有让同步代码等到异步代码完成。

在您的代码中,如果启用注释 setState 调用,该代码将在异步代码等待响应时执行。

你需要setState里面:

searchResults.orderByChild('location').equalTo(location).on('value', (snap) => {
    let users = snap.val();
    const profiles = Object.keys(users).map((key) => users[key]);
    this.setState({ users: profiles[0] });
});

每当你想要在异步代码之后执行某些东西时,将其放在 callback (to the async fn) or use a Promise.


What would be the best way to get the data back from the state? How do I loop through objects in the state?

setState 也可以是异步的。但是您将在下一次渲染时获得新的更新状态。因此,在 render() 中,您可以在 this.state.users 状态下访问 users 并使用它执行操作。

更新:

componentWillMount(){
    const searchResults = FBAppDB.ref('users');
    const location = this.props.location;
    const instrument = this.props.instrument;

    searchResults.orderByChild('location').equalTo(location).on('value', (snap) => {
        const users = snap.val();
        const profiles = Object.keys(users).map((key) => users[key]);

        // previously we were setting just profiles[0]; but I think you need 
        // the entire list of users as an array to render as search results
        this.setState({ users: profiles }); // set the whole data to state
    });
}


render(){
    const users = this.state.users || []; // note that this.state.users is an array

    return(
        <Row>
            {
              users.length > 0 
              ? users.map((user) => <SearchResult user={user} />)
              : null
            }
        </Row>
    );
}