【问题标题】:Why connect from react-redux doesn't send the new state as props to the my component?为什么从 react-redux 连接不会将新状态作为道具发送到我的组件?
【发布时间】:2020-07-04 13:59:04
【问题描述】:

我在 The Net Ninja Youtube 频道上关注 firebasetutorial,我在将 Redux 中的 store 的数据连接到我的组件时遇到问题,我知道数据将来自firestore 不是立即异步异步的,所以我假设props.projects 将以[] 开始,然后一段时间后它将从firestore 变为真实数据,在记录mapStateToProps 时,状态在mapStateToProps 中成功更改state.firestore.ordered.projects 但是尽管使用了 react-redux 的连接,但在记录 props.projects 时从未发生过这种情况,我真的不知道为什么会发生这种情况:

这是我的代码:

import React from 'react';
import { connect } from 'react-redux';
import { firestoreConnect } from 'react-redux-firebase';
import { compose } from 'redux';
import ProjectList from '../Projects/ProjectList';
import Notifications from './Notifications';

function Dashboard(props) {
    console.log('p', props.projects)
    return (
        <div className="dashboard container">
            <div className="row">
                <div className="col s12 m6">
                  <ProjectList projects={props.projects} />
                </div>
                <div className="col s12 m5 offset-ml">
                    <Notifications />
                </div>
            </div>
        </div>
    )
}

const mapStateToProps = (state) => {
    console.log(state.firestore.ordered.projects)
    return {
        projects: state.firestore.ordered.projects || []
    }
}

export default compose(
    connect(mapStateToProps),
    firestoreConnect([{collection: 'Projects'}])
)(Dashboard);

projectAction.js:

export const createProject = (project) => {
    return (dispatch, getState, { getFirebase, getFirestore }) => {
        const firestore = getFirestore();
        firestore.collection('Projects').add({
            ...project,
            createdAt: new Date()
        }).then(() => dispatch({
            type: 'CREATE_PROJECT',
            project
        })).catch(err => dispatch({
            type: 'CREATE_ERROR',
            err
        }))
    }
}

为什么connect在这里不起作用,并且一旦发生变化就不将数据绑定到组件??

【问题讨论】:

  • 需要明确的是,在 mapStateToProps 中,您会看到 state.firestore.ordered.projects 从无到有更新为 Firebase 中的一系列文档,但在 Dashboard 中,您不会看到 props.projects 更新为相同的值?
  • 是的,这正是我在这里所经历的@BlunderingPhilosopher
  • 我认为如果您的收藏有大写 P (Projects),您应该访问 state.firestore.ordered.Projects(注意大写 P)。除此之外,我没有发现任何问题:/

标签: reactjs firebase redux google-cloud-firestore react-redux


【解决方案1】:

最初,prop projects 是空的。但是当从 firestore 获取数据时,组件已经被渲染。因此,要更新它,请使用 useEffect 并将 props.projects 作为依赖项。

useEffect(() => {}, [props.projects])

【讨论】:

  • DashboardProjectList 组件中尝试 useEffect 挂钩。
  • 如果这回答了您的问题,您可以将其标记为已回答。
猜你喜欢
  • 2022-01-16
  • 1970-01-01
  • 1970-01-01
  • 2021-10-25
  • 1970-01-01
  • 1970-01-01
  • 2017-11-20
  • 2016-09-10
  • 2022-01-23
相关资源
最近更新 更多