首页 > 解决方案 > 如何调度构造函数中的更改?

问题描述

我正在尝试学习 redux。我认为我的 reducer 很好,我可以从 store 中提取数据并通过 props 设置它。

但是我无法将注意力集中在操作和更改商店状态的数据上。

我有这个:

const mapDispatchToProps = (dispatch) => {
    return{
        what goes in here?
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(ComponentName);

我需要知道如何在 const 中发送更改。只是一个简单的将文本添加到空状态。示例:状态是 apples:'',我想在其中添加 '红色美味'。

标签: reactjsredux

解决方案


mapDispatchToProps为您提供了一种访问connect组件action creators的方法。假设您有一个增加counter状态的动作创建者

export const change = value =>({
    type: 'CHANGE_FRUIT',
    fruit : value
})

并且您想value从您的组件之一传递。首先connect像你已经在做的那样在这个组件中使用 HOC。现在您需要incrementCounter从您的actions文件夹中导入

import { change as changeFruit } from './actions/fruit'

现在mapDispatchToProps像这样使用

const mapDispatchToProps = dispatch =>({
    change : fruit => dispatch(changeFruit(fruit))
})

现在您action creator在组件内部有一个序列化props,当您调用它时,props.increment(2)这将等同于调用

dispatch(changeFruit('apple'))

这就是为什么您应该始终这样做props.increment而不是直接dispatch在组件内部调用的原因。

所以你的组件内部的完整实现可能是这样的

import { change as changeFruit } from './actions/fruit'

class Component extends React.component{
    render(){
        const { fruit, change } = this.props
        return(
            <>
                <div>{fruit}</div>
                <button onClick={() => change('orange')}>Change to orange</button>
            </>
        )
    }
}

const mapStateToProps = state =>({
    fruit : state.fruit
})

const mapDispatchToProps = dispatch =>({
    change : fruit => dispatch(changeFruit(fruit))
})

export default connect(mapStateToProps, mapDispatchToProps)(Component)

你的减速器应该是这样的

const initialState = {
    fruit: 'apple'
}

export const reducer = (state = initialState, action) =>{
    switch(action.type){
        case 'CHANGE_FRUIT' : return{
            ...state,
            fruit : action.fruit
        }

        default : return state
    }
}

推荐阅读