反应redux重新渲染不是由状态改变触发的

时间:2020-01-28 01:41:00

标签: javascript reactjs redux react-redux

我开始学习react和react-redux,但是我无法理解组件或容器如何了解状态更改并随后重新呈现。我尝试了一个简单的示例,但无法使其按预期方式工作。我正在尝试做的是显示一个计数器和一个按钮。每次单击按钮,计数器应递增。单击按钮可分派操作并更改状态,但不知何故计数器不会显示在屏幕上。它甚至没有显示0计数器的初始状态。我对前端开发也很陌生,所以也许它与redux无关,但与React无关。

这是我的 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 动作和减速器

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"}
}

1 个答案:

答案 0 :(得分:5)

您在counterReducer内定义的计数器状态已针对tmp键进行了注册

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

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

所以应该像

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

代替

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