簡體   English   中英

我可以使用操作和減速器來更新狀態,但是當我嘗試對其引發的操作執行onClick時,可以在組件上更新狀態

[英]I am able to update the state using action and reducer but on the component when I try to do onClick for the action it throws

    ` import React, { Component, PropTypes } from 'react';
       import { connect } from 'react-redux';
        import { itemsFetchData } from '../actions/sidenavaction';

       class SideNavItem extends Component {
            componentDidMount() {
           this.props.fetchData('http:
           //58f5d2ccc9deb71200ceecef.mockapi.io/nav');
            }

          render() {    
          var Nest=function(par) {
                const numbers = par.itemized;
                const listItems = numbers.map((number) => <li key=
           {number.sid}>{number.svalue}</li>);
                return (<ul>{listItems}</ul>);
            };



             if (this.props.hasErrored) {
               return <p>Sorry! There was an error loading the items</p>;
               }

           if (this.props.isLoading) {
        return <p>Loading…</p>;
              }

           return (
        <ul>{this.props.items.map((item) =>         
        <ul key={item.id} onClick={this.props.toggleDiv}><a href="#">
           {item.value}</a>
            {item.sub && <Nest itemized={item.sub} />}          
        </ul>               
        )}
        </ul>
            );          
          }
             }

        const mapStateToProps = (state) => {
      return {
     items: state.items,
     hasErrored: state.itemsHasErrored,
     isLoading: state.itemsIsLoading
           };
            };

         const mapDispatchToProps = (dispatch) => {
               return {
             fetchData: (url) => dispatch(itemsFetchData(url)),
                toggleDiv: () => dispatch(toggleDiv())
            };
       };

              export default connect(mapStateToProps, mapDispatchToProps)
        (SideNavItem);`

在on Click函數上,我正在將toggleDiv動作傳遞給道具,但是單擊我的屏幕上的標簽時,它會拋出未定義的錯誤toggleDiv。狀態也被我要使用動作和reducer(動作)傳遞的值更新
export function toggleDiv(){ return { type: 'TOGGLE_DIV' }; }

(reducer)`導出功能toggleDivReducer(state = {hidden:true},action){switch(action.type){

        case 'TOGGLE_DIV':
        return Object.assign({}, state, {hidden: !state.hidden});

            default:
            return state;

          }

           }`

您只導入itemsFetchData操作,而不是toggleDiv ,因此當mapDispatchToPropstoggleDiv不會是未定義的

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM