【发布时间】:2020-01-20 20:51:24
【问题描述】:
我有一个小问题,这是我第一次使用 redux,我正在尝试编辑我的标题,所以这是我拥有的两个组件:(我在下面解释了我期望看到的但没有得到它)
import React, { Component } from 'react';
import { connect } from "react-redux";
import { changeTitle } from "./redux/actions/changeTitle"
import { bindActionCreators } from "redux";
class Test extends Component {
constructor(props) {
super(props);
this.state = {}
}
render() {
return (
<div>
<h1>{this.props.myTitle}</h1>
<button onClick={() => this.props.changeTitle("That")}>Change</button>
</div>);
}
}
function mapStateToProps(state) {
return {
myTitle: state.title
};
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({
changeTitle: changeTitle
}, dispatch)
}
export default connect(mapStateToProps, mapDispatchToProps)(Test);
这是我第一次获得标题的方法:
export default function titleReducer(state, action) {
if (action.type !== "TITLE_CHANGED") {
console.log(state);
console.log(action);
return "qlq"
} else {
return state
}
}
这是我的 changeTitle 减速器:
export default function titleChangeReducer(state, action) {
if (action.type === "TITLE_CHANGED") {
console.log(state);
console.log(action);
return {
title: "test again", ...state
}
}
return [];
}
所以我希望当我改变状态时,我会直接改变我的视图,但老实说,即使我改变了我的状态,我也不知道,当我点击我的按钮时,console.log 会给我什么:
{title: "再次测试"} {类型:“TITLE_CHANGED”,有效载荷:“那个”}
这是我的更改标题操作:
export function changeTitle(toThat) {
return {
type: "TITLE_CHANGED",
payload: toThat
}
}
这是我如何组合我的减速器:
import { combineReducers } from "redux";
import titleReducer from "./titleReducer";
import titleChangeReducer from "./titleToChange";
const rootReducer = combineReducers({
title: titleReducer,
titleChanging: titleChangeReducer
})
export default rootReducer;
如果还有什么要补充以使问题更清楚,请让我补充。
任何帮助将不胜感激。
【问题讨论】:
-
有两个与title相关的reducer的原因是什么?
-
没有理由,我以为不会有问题,你认为是问题吗?因为我注意到我的 redux 状态在组件中没有改变。
-
嗯,我想这取决于您期望第二个减速器如何工作。拥有它并没有什么问题,我只是确保您不会尝试使用它来更新第一个减速器。
-
嗯,是的,大声笑,我正在使用它对第一个进行更改
-
啊,那是个问题。它们是您整体状态的两个独立部分。两者都可以监听相同的动作,但它们不能互相修改状态的一部分
标签: reactjs redux react-redux