【发布时间】:2019-04-05 08:42:53
【问题描述】:
编辑:我解决了我的问题,它现在对我有用 - 还编辑了我的代码以反映新的变化。
我收到此错误,但我不确定此错误的原因。
因为是公司的材料所以无法展示代码,所以我会尽力描述它:
App.js:
`class App extends React.Component {
constructor(props) {
super(props);
}
render () {
return (
<div>
<Header />
<RouteList />
<Footer />
</div>
)
}
}`
我的<RouteList /> 是一个无状态函数,它返回网络应用程序的所有路由。
Header.js:
class Header extends React.Component {
constructor (props) {
super(props);
this.changeHeader = this.changeHeader.bind(this);
}
changeHeader(headerType) {
this.props.actions.changeHeader(headerType)
}
GetHeader() {
// if-else statement which will return a different sub header class
const HeaderType = this.props.renderHeader.headerType
if (headerType == 'abc') {
<aHeader changeHeader={this.changeHeader} />
} [...] {
// Final else block return something
}
}
render () {
return (
<div>{this.GetHeader()}</div>
)
}
}
function mapStateToProps(state, ownProps) {
return { renderHeader: state.renderHeader};
}
function mapDispatchToProps(dispatch) {
return { actions: bindActionCreators(headerActions, dispatch) };
}
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Header));
this.props.action.changeHeader(headerType) 是一个 if-else 语句,根据 headerType 的值,将触发不同的操作。
state.renderHeader 在我的 rootReducer 中声明。
我将changerHeader() 传递给无状态的单个 header.js(即 aHeader.js、bHeader.js ...)。单击导航链接时,它将调用该方法并将页面路由到另一个 UI。这就是我将方法嵌入导航链接的方式:onClick={changeHeader(input')}。
rootReducer.js
const rootReducer = combineReducers({renderHeader});
export default rootReducer;
renderHeader就是renderHeaderReducer。
headerAction.js
export function changeHeader(headerType) {
if (headerType == "abc") {
return {type: type, headerType: "abc"}
} [...] {
// something default
}
}
renderHeaderReducer.js
export default function renderHeaderReducer(state = initialState, action) {
switch(action.type) {
case "abc":
return (Object.assign({}, ...state, {headerType: action.headerType}));
[...];
default:
return state;
}
}
此时单击链接时,Web 浏览器应刷新,将 Header 留在原处但修改部分。但是我的网站进入了一个无限循环,错误是:
错误:在现有状态转换期间无法更新(例如在渲染或其他组件的构造函数中)。渲染方法应该是 props 和 state 的纯函数;构造函数副作用是一种反模式,但可以移动到 componentWillMount。
当我执行 console.log 以查看发生了什么时,它似乎正在循环我定义的所有各种选项,这些选项将呈现 Header.js
事实证明,主要问题是当我调用我的 onClick 方法时。导致我的代码出错的无限循环是 onClick 函数触发的结果,即使没有被点击。
原文:onClick={this.changeHeader('abc')}
新:onClick={() => changeHeader('abc')}
请参阅此post 以获得解释。
谢谢。
【问题讨论】:
-
你说 state.renderHeader 是在你的 rootReducer 中声明的;但是,您不应该从代码中调用 reducer 函数。相反,您应该调用操作,这反过来会触发适当的 reducer 函数来修改您的状态。
-
@sme 我调用了这个动作
this.props.actions.changeHeader(headerType) -
您是否在任何地方调用
renderHeader函数?我仍在试图弄清楚这是否对您的代码有影响。但同样,如果它是一个 reducer 函数,它不应该在你的 mapStateToProps() 函数中。 -
@sme,我没有在其他任何地方调用我的 renderHeader 函数。我认为 mapStateToProps() 函数应该将减速器映射到道具?
-
mapStateToProps 应该只用于从你的 redux 存储(状态)传递属性,或者通过
ownProps直接传递给组件的属性。动作创建者应该在 mapDispatchToProps() 中,据我所知,这在您的代码中是正确的。一旦调用了动作创建函数,它将创建动作,然后根据动作包含的type属性自动调用适当的reducer。你不需要手动调用任何reducer,也不需要将它们传递给任何组件
标签: reactjs redux react-redux react-router-v4