所有
我是Redux的新手,当我尝试初始化应用程序的状态时,我想直接将store.getState()
提供给App组件的this.setState()
,但它一直给我一些错误
"在现有状态转换期间无法更新(例如
render
内)。"
我的代码就像:
import React, { Component } from 'react'
import { createStore } from 'redux'
var headerMenuReducer = (state, action) => {
switch (action.type) {
case "OPEN_MENU": {
state.data.forEach(function(menu, i){
if(menu.id == action.id ){
menu.active = true;
} else {
menu.active = false;
}
})
return state;
}
case "CLOSE_MENU": {
state.data.forEach(function(menu, i){
menu.active = false;
})
return state;
}
default: {
return {
data: [
{
type: "menu",
title: "Views",
id: "menu_views",
active: false
},
{
type: "menu",
title: "Portfolios",
id: "menu_portfolios",
active: false
},
{
type: "menu",
title: "Factors",
id: "menu_factors",
active: false
},
{
type: "menu",
title: "Tools",
id: "menu_tools",
active: false
},
{
type: "link",
title: "Information",
id: "menu_infomation",
active: true
}
]
}// end of return
}
}
}
let store = createStore(headerMenuReducer);
class App extends React.Component {
constructor(props) {
super(props);
this.state = {data:[]};
this.style={
"padding": "0 5px"
}
}
componentDidMount(){
this.setState(store.getState());
}
activeMenu(id) {
store.dispatch({
type: "OPEN_MENU",
id: id
})
this.setState( store.getState() )
}
render(){
return (
<div>
{
this.state.data.map( (menu, i) => {
var style = Object.assign({}, this.style, {"backgroundColor": (menu.active?"lightblue": "lightpink")})
return <span key={menu.id} style={style} onClick={this.activeMenu(menu.id).bind(this)}>{menu.title}</span>
})
}
</div>
)
}
}
export default App
答案 0 :(得分:2)
问题出在这个组件定义中:
<span key={menu.id} style={style} onClick={this.activeMenu(menu.id).bind(this)}>{menu.title}</span>
您在呈现时调用 activeMenu()
。我的猜测是你想在点击时调用它。
为此,我建议将span
作为自己的组件,并在其内部调用传递的prop回调 - 相应地传递特定的id。
这样的事情:
const MenuButton = ({ id, title, onClick}) => (
<span key={id} onClick={() => { onClick(id) }>{title}</span>
);
class App extends React.Component {
constructor(props) {
//...
},
activeMenu(id) {
//...
},
render() {
const menuButtons = this.state.data.map((menu, i) => {
return <MenuButton id={menu.id} title={menu.title} onClick={this.activeMenu}>
});
return (
<div>
{menuButtons}
</div>
)
}
}
(取出你的风格逻辑,让这个例子更容易理解。)