第一个小反应/减少项目,以学习反应和减少。
按钮元素上的onClick事件会触发,因为我可以在控制台中看到该值(在reducer文件中)。但是,视图未更新。
是的,我已经在网上看过了,我已经被困在这个问题上一整天了。
我做错了什么?
提前致谢。
PanelContainer.js文件:
class PanelContainer extends React.Component {
constructor(){
super();
this.state = {
color: new Color()
}
}
render(){
return (
<div class="container">
<Row>
<Cell cols={`col-sm-12 col-md-3 col-lg-3`}>
<Panel>
<PanelBody color={this.state.color.generateColor(new Gray())}>
<Title title={this.props.follower.count} />
<p>{this.props.follower.description}</p>
<p><button class="btn btn-primary" onClick={() => this.props.getFollower()}>Update</button></p>
</PanelBody>
</Panel>
</Cell>
</Row>
</div>
);
}
}
const mapStateToProps = (state) => {
return {
follower: state.followerReducer
};
};
const mapDispatchToProps = (dispatch) => {
return {
getFollower: () => {
dispatch(getFollower());
},
changeFollower: () => {
dispatch(changeFollower());
}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(PanelContainer);
FolloweReducer.js文件:
export default (state = { follower: { count: 0, description: "Default description" } }, action) => {
switch(action.type){
case "GET_FOLLOWER":
state = { ...state, follower: action.payload };
console.log("GET FOLLOWER", state);
break;
case "CHANGE_FOLLOWER":
state = { ...state, follower: action.payload };
console.log("CHANGE FOLLOWER", state);
break;
default:
break;
}
return state;
};
FollowerAction.js文件:
export function getFollower() {
return {
type: "GET_FOLLOWER",
payload: {
count: 20,
description: "New followers added this month"
}
}
}
export function changeFollower(){
return {
type: "CHANGE_FOLLOWER",
payload: {
count: 50,
description: "Changed Followers!!!"
}
}
}
Store.js文件:
const store = createStore(combineReducers({
followerReducer: followerReducer
}));
export default store;
App.js文件:
import React from "react";
import ReactDom from "react-dom";
import {Provider} from "react-redux";
import PanelContainer from "./panel/PanelContainer";
import store from "./shared/Store";
let app = document.getElementById("app");
ReactDom.render(
<Provider store={store}>
<PanelContainer />
</Provider>,
app
);
答案 0 :(得分:2)
我相信你在渲染视图中没有看到任何更新的原因是因为你错误地将你的状态映射到你传递给组件的道具。 你state-&gt; props映射函数应该是:
const mapStateToProps = (state) => {
return {
follower: state.followerReducer.follower
};
};
state.followerReducer
是您的reducer管理的整个状态对象。
从这一行可以清楚地看出
state = { ...state, follower: action.payload };
并从您的初始状态定义中将您更新的数据存储在state.followerReducer.follower
使用您拥有的mapStateToProps
函数,render方法中的{this.props.follower.count}
将是整个reducer对象({follower: {...}}
。
答案 1 :(得分:0)
Redux不更新视图的另一种情况是,您需要:ReduxPersist
尝试一下,我救了我的命。
答案 2 :(得分:0)
(深度解决方案):我建议阅读这篇文章:
(快速解决方案):我建议使用此代码来解决问题:
return {
follower: Object.assign({},follower: state.followerReducer.follower}
};