【问题标题】:Updating redux state onClick更新 redux 状态 onClick
【发布时间】:2019-10-19 11:53:13
【问题描述】:

我有一个显示状态数据的组件。我正在使用 redux 作为状态。我希望能够单击一个按钮并过滤状态。但我坚持从按钮调度动作。

现在我有一个按钮应该调度操作,但它没有被调用。我不确定 mapsToDispatchProps 是错误的还是其他原因。

这里是动作

import { GET_POLLS, SHOW_APPROVAL } from './types';


const URL = 'https://projects.fivethirtyeight.com/polls/polls.json';

export const getPolls = () => dispatch => {

    return fetch(URL)
        .then(res => res.json())
        .then(polls => {
            dispatch({ type: GET_POLLS, payload: polls })
        })


}

export const getApproval = () => ({ type: SHOW_APPROVAL }) 

减速器

import {
    GET_POLLS,
    SHOW_APPROVAL
} from '../actions/types';



const pollReducer = (state = [], { type, payload }) => {
    switch (type) {
        case GET_POLLS:
            return payload
        case SHOW_APPROVAL:
            return (payload.type === "trump-approval")
        default:
            return state
    }
}

export default pollReducer;

类型

export const GET_POLLS = 'GET_POLLS';
export const POLLS_LOADING = 'POLLS_LOADING';
export const SHOW_ALL = 'SHOW_ALL';
export const SHOW_APPROVAL = 'SHOW_APPROVAL';

显示数据的列表

import React, { Component } from 'react'
import { PollCard } from '../Components/PollCard'
// import FilterLink from './FilterLink'
import * as moment from 'moment';

import { connect } from 'react-redux'
import { getPolls, getApproval } from '../actions/index';

class PollList extends Component {

    componentDidMount() {
        this.props.getPolls();
    }



    render() {


        console.log("rendering list")
        const { polls } = this.props

        const range = 30
        var dateRange = moment().subtract(range, 'days').calendar();
        var filteredPolls = polls.filter(e => Date.parse(e.endDate) >= Date.parse(dateRange)).reverse()



        return (

            <React.Fragment>
                <button onClick={getApproval}>
                    Get Approval

                </button>
                {console.log("get approval", getApproval)}


                {
                    filteredPolls && filteredPolls.map((poll) => (
                        <div key={poll.id}>
                            <PollCard poll={poll} />

                            {/* {(poll.type)} */}

                        </div>
                    ))




                }
            </React.Fragment>

        )
    }
}

const mapStateToProps = state => ({
    polls: state.polls
});

const mapDispatchToProps = {
    getApproval
};

export default connect(
    mapStateToProps,
    mapDispatchToProps,
    { getPolls, getApproval }
)(PollList);


// export default PollList;

【问题讨论】:

  • 嗨!刚刚为您提供了一个解决方案,如果对您有帮助,请告诉我。

标签: javascript reactjs redux


【解决方案1】:

您的mapDispatchToProps() 似乎配置不正确。您需要定义一个返回objectfunction,为您希望在组件中作为prop 提供的每个action 定义一个键值对。

const mapDispatchToProps = (dispatch) => {
   return {
      getApproval: () => {
         dispatch(getApproval())
      },
      getPolls: () => {
         dispatch(getPolls())
      }
   }
}

export default connect(
    mapStateToProps,
    mapDispatchToProp)(PollList);

现在 getPolls 可以作为 prop 使用,您可以在 componentDidMount() 中使用它

componentDidMount() {
    this.props.getPolls();
}

您还应该为您的 getApproval 操作创建一个 onClick 处理程序

handleClick = () => {
   this.props.getApproval()
}

然后将其连接到您的 onClick 事件监听器

<React.Fragment>
    <button onClick={this.handleClick}>
        Get Approval
    </button>
    console.log("get approval", getApproval)}
    {
        filteredPolls && filteredPolls.map((poll) => (
           <div key={poll.id}>
              <PollCard poll={poll} />
                 {/* {(poll.type)} */}
           </div>
        ))
    }
</React.Fragment>

动作文件

export const getPolls = () => dispatch => {
      fetch(URL)
        .then(res => res.json())
        .then(polls => {
            dispatch({ type: GET_POLLS, payload: polls })
        })
        .catch(errors => {
            dispatch({ type: "GET_ERRORS", payload: errors.response.data })
        })
}

减速器

import {
    GET_POLLS,
    SHOW_APPROVAL
} from '../actions/types';

const pollReducer = (state = [], { type, payload }) => {
    switch (type) {
        case GET_POLLS:
            return payload
        case SHOW_APPROVAL:
            return state.filter((poll) => {
                return poll.type === "trump-approval"
            })
        case "GET_ERRORS":
            return payload
        default:
            return state
    }
}

export default pollReducer;

【讨论】:

  • 我在 mapDispatchToProps 的 dispatch 下得到一条红线
  • @jhaywoo8 哦,对不起,我忘了将 dispatch 作为参数传递。你现在可以试试我更新的解决方案吗:)
  • 现在我收到此错误“TypeError: Cannot read property 'type' of undefined”
  • @jhaywoo8 很好。我们即将推断出什么是错的。看起来该动作现在确实被调用了。您的有效负载(从后端返回的数据)是否有一个名为 type 的键?民意调查是数组还是对象?听起来像是一个数组。
  • 现在用新代码得到这个错误:“错误:给定动作“SHOW_APPROVAL”,reducer“polls”返回未定义。要忽略一个动作,你必须明确地返回以前的状态。如果你想要这个reducer 不保存任何值,你可以返回 null 而不是 undefined。”
【解决方案2】:

你没有调用动作函数。

// Either destructure it
const { polls, getApproval } = this.props;
<button onClick={getApproval}>
    Get Approval
</button>
// Or use this.props.function
<button onClick={this.props.getApproval}>
    Get Approval
</button>
// You don't need this
const mapDispatchToProps = {
    getApproval
};
// You don't need this

const mapStateToProps = state => {
    return {polls: state.polls};
};
export default connect(
    mapStateToProps,
    // Doing this is easier, cleaner & faster
    { getPolls, getApproval }
)(PollList);

你做对了;

componentDidMount() {
    this.props.getPolls();
}

【讨论】:

  • 我收到此错误:“TypeError: Cannot read property 'type' of undefined”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-01-25
  • 1970-01-01
  • 1970-01-01
  • 2018-02-11
  • 2019-07-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多