【问题标题】:React-redux no result apearsReact-redux 没有结果出现
【发布时间】:2021-01-26 22:20:49
【问题描述】:

我正在使用 React redux 构建一个可以加减的数字的 div。 enter image description here

问题是一切看起来都不错 但是浏览器上没有结果

reducer-> index.js:

    import { combineReducers } from 'redux'
    
    const sumReducer = (sum = 0, action) => {
        if (action.type === 'ADD' || action.type === 'SUB') {
            let x = action.payload;
            return x;
        }
    
        return sum;
    }
    
    export default combineReducers({
        sum: sumReducer
    });

**action-> index.js**

export const add = (sum) => {
    return {
        type: 'ADD',
        payload: sum + 1
    }
}

export const sub = (sum) => {
    return {
        type: 'SUB',
        payload: sum  - 1
    }
}

我的组件是:upDownSum.js

    import React from 'react'
    import { connect } from 'react-redux'
    import { add, sub } from '../action'
    
    class UpDownSum extends React.Component {
        render() {
            console.log(this.props);
            console.log("ghj");
            return (
                <div key="1">
                    <button onClick={() => sub(this.props.sum)}>-</button>
                    <div>{this.props.sum}</div>
                    <button onClick={() => add(this.props.sum)}>+</button>
                </div>
    
            )
        }
    }
    const MapStateToProps = (state) => {
        return {
            sum: state.sum
        }
    }
    
    export default connect(MapStateToProps, {add: add ,sub: sub})(UpDownSum);

app.js 导入'./App.css'; 从'./upDownSum'导入UpDownSum

function App() {
  return (
    <UpDownSum/>
  );
}

export default App;

谢谢!

【问题讨论】:

    标签: reactjs redux action connect


    【解决方案1】:

    您正在将 dispatch 映射到 props,这意味着您需要确保使用 props 而不仅仅是导入的动作来调度动作:

    return (
      <div>
        <button onClick={() => this.props.sub(this.props.sum)}>-</button>
        <div>{this.props.sum}</div>
        <button onClick={() => this.props.add(this.props.sum)}>+</button>
      </div>
    )
    

    【讨论】:

    • 那我该怎么办?
    • 请注意,我将 sub 更改为 this.props.subadd 更改为 this.props.add
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-02
    • 1970-01-01
    • 2021-09-20
    • 1970-01-01
    • 1970-01-01
    • 2016-04-16
    相关资源
    最近更新 更多