【问题标题】:react redux re-render not triggered by state-changereact redux re-render 不是由 state-change 触发的
【发布时间】:2020-05-13 10:05:19
【问题描述】:

我开始学习 react 和 react-redux,但我无法理解组件或容器如何知道状态变化并重新渲染。我尝试了一个简单的示例,但无法让它按应有的方式工作。我想要做的是显示一个计数器和一个按钮。每次单击按钮时,计数器都会增加。按钮单击调度一个动作并且状态改变,但不知何故计数器没有显示在屏幕上。它甚至没有显示带有 0 计数器的初始状态。我对前端开发也很陌生,所以也许它与 redux 无关,但与反应有关。

这是我的 index.js

import store from "./store/configureStore"

render(
<Provider store={store}>
    <Countercont></Countercont>
</Provider>
, document.getElementById('root'));

configureStore.js

import {combineReducers, createStore} from 'redux'
import counterReducer from "./modules/counter"

const reducer = combineReducers({
    tmp: counterReducer });

const configureStore = createStore(reducer)
export default configureStore;

Mycounter.js

const Mycounter = ({counter, inc}) => (
<div>
    <p>"counter"</p>
    <p>{counter}</p>
    <Button onClick={inc}>Inc</Button>
</div>
)

export default Mycounter

countercont.js容器组件

const Countercont = ({counter, inc}) => {
    return (
        <div>
            <Mycounter counter={counter} inc={inc}/>
        </div>
    )
}
const mapStateToProps = state => {
    return {counter: state.counter};
};

const mapDispatchToProps = dispatch => {
    return {inc: () => dispatch(inc())}
};

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

counter.js动作和reducer

export default function reducer(state = {counter: 0}, action) {
    console.log(state) //-> shows the correct state
    switch (action.type) {
        case "c":
            console.log("Inc")
            return {...state, counter: state.counter + 1}
        default:
            return state
    }
}

export function inc() {
    return {type: "c"}
}

【问题讨论】:

    标签: javascript reactjs redux react-redux


    【解决方案1】:

    您在counterReducer 中定义的计数器状态是针对tmp 键注册的

    const reducer = combineReducers({
       tmp: counterReducer
    });
    

    因此,为了获得该值,您的组件 mapStateToProps 回调应该使用您的 reducer 键(代码中的 tmp)从整个状态中获取该值

    应该是这样的

    const mapStateToProps = state => {
        return {counter: state.tmp.counter};
    };
    

    而不是

    const mapStateToProps = state => {
        return {counter: state.counter};
    };
    

    【讨论】:

    • 这条评论是正确的,“tmp”在 combineReducers 中被声明为 key。
    • 非常感谢。我不知道钥匙实际上很重要!但是现在可以了!
    猜你喜欢
    • 2021-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-29
    • 1970-01-01
    • 2018-12-04
    相关资源
    最近更新 更多