【问题标题】:MERN & Redux: How do you pass Redux state data from Index to Show page?MERN & Redux:如何将 Redux 状态数据从 Index 传递到 Show 页面?
【发布时间】:2020-04-25 22:03:38
【问题描述】:

--短版 我的索引页面是所有锦标赛的列表。每个人都有一个按钮,您可以单击以转到该锦标赛的页面。 在每个锦标赛的索引中,我有一个按钮,其中包含 onClick={} 在 Redux 中选择锦标赛数据的操作。

如何在下一页正确访问该状态数据?

--长版 我有一个锦标赛模型,其中包含在后端编写的用于完整 CRUD 的大量快速路线。

我还写了 redux.. 我得到了索引页面(数据库中所有锦标赛的列表) 我将展示我的 GET ALL TOURNAMENTS 代码,以便您了解我是如何过渡到创建 SHOW ONE TOURNAMENT 代码的。

后端 ExpressJS 路由

// @route       GET /tournaments
// @descrip Get All, INDEX
// @access  Public
router.get('/', (req, res) => {
    Tournament.find()
        .sort({ date: -1 })
        .then(tournaments => res.json(tournaments))
        .catch(err => console.log(err));
});

减速器

const initialState = {
    tournaments: [],
    loading: false
}

case GET_TOURNAMENTS:
    return {
        ...state,
        tournaments: action.payload,
        loading: false
    };

动作

export const getTournaments = () => dispatch => {
    dispatch(setTourneysLoading()); 
    axios
        .get('/tournaments')
        .then(res => dispatch({
            type: GET_TOURNAMENTS,
            payload: res.data
        }))
        .catch(err => dispatch(returnErrors(err.response.data, err.response.status)));
};

好的..感谢您的耐心等待!这是我为 SHOW 准备的内容

快速路线

// @route   SHOW /tournaments/:id
// @descrip Display a single tournament
// @access  Public
router.get('/:id', (req, res) => {
    Tournament.findById(req.params.id)
        .then(tournament => res.json(tournament))
        .catch(err => res.status(404).json({ msg: "Tournament not found" }));
});

减速器

case DISPLAY_TOURNAMENT:
    return {
        ...state,
        // Iterate through tournaments to find one that matches payload
        tournaments: state.tournaments.map(tournament => tournament._id === action.payload ?
            // display that tournament
            { tournament } :
            // else, display nothing
            null
        ),
        loading: false
    };

动作

export const showTournament = id => dispatch => {
    dispatch(singleTourneyLoading());   
    axios
        .get(`/tournaments/${id}`)
        .then(() => dispatch({
            type: DISPLAY_TOURNAMENT,
            payload: id
        }))
        .catch(err => dispatch(returnErrors(err.response.data, err.response.status)));
};

我是否只需要为此创建一个新的减速器? 我可以看到州内显示的锦标赛。在前端,我试图从 State 中提取它,以便我可以使用 PropTypes 呈现数据。

我不想把这篇文章写得很大,但我会把我的节目文件放在这里,这样一切都公开了

import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import TournamentDescription from './descriptions';
import { showTournament } from '../../actions/tournamentActions';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
class TournamentShow extends Component {
    componentDidMount() {
        this.props.showTournament(this.props.tournament._id);
    };
    static propTypes = {
        showTournament: PropTypes.func.isRequired,
        tournament: PropTypes.object.isRequired,
        auth: PropTypes.object.isRequired
    };
    render() {
        const { _id, title, hostedBy, status, participants } = this.props.tournament;
        return (
            <div>
                <h1>{ title }</h1>
                <h3> <TournamentDescription key={_id} title={ title } /> </h3>
                <p>status: { status }</p>
                <p>Registered Fighters:
                    {
                        participants.map((participant, index) => {
                            return (
                                <ul key={ index }>
                                    <li>{ participant }</li>
                                </ul>
                            )
                        })
                    }
                </p>
                <p>Hosted by: { hostedBy }</p>
                <Link to="#">Sign Up</Link>
                <Link to="/">Back to Tournaments main page</Link>
            </div>
        )
    }
};
const mapStateToProps = state => ({
    tournament: state.tournament.tournaments[0],
    auth: state.auth
});
export default connect(mapStateToProps, { showTournament })(TournamentShow);

谢谢大家

【问题讨论】:

    标签: javascript reactjs express redux mern


    【解决方案1】:

    如果状态中有tournament 数据,可以直接使用 this.props,并且还使用TournamentShow 类中的componentDidUpdate 函数。您可以验证该值是否已更新,在下一个示例中,我使用 equals 库来比较锦标赛属性的值:

    componentDidUpdate(prevProps) {
        if(!equal(this.props.tournament, prevProps.tournament)) {
          //Some operations with tournament value
        }
      }
    

    【讨论】:

    • 我现在要试试这个。我有用于在 AllTournaments 组件中获取 Show Tournament(id) 的 Reducer 操作是否有意义?我需要在两个组件中使用 ShowTournament Action 吗?
    • 我的猜测是 ShowTournament 只应该在一个组件(TournamentShow)中调用,如果在两个组件中调用 ShowTournament,响应将是相同的,但会执行不必​​要的请求.另一方面,您可以在 reducer 上使用 find 而不是 mapstate.tournaments.find(tournament =&gt;tournament._id === action.payload ? {tournament}: null 返回单个结果。
    • 啊,这是一个很棒的提示。这将返回我在数据中选择的正确锦标赛。当我单击激活 showTournament() 的按钮时,我收到了 Cannot read property of undefined。似乎有些东西没有正确通过.. 我很确定我以某种方式离开了
    猜你喜欢
    • 1970-01-01
    • 2019-02-17
    • 2020-10-29
    • 2019-08-19
    • 1970-01-01
    • 1970-01-01
    • 2016-01-19
    • 2017-01-26
    • 2019-04-01
    相关资源
    最近更新 更多