我有一个变量attackHero
,其初始值为Ironman。它在页面上正确显示。单击按钮后,我将通过 Redux 调度将其更改为 Hulk。但更改并未反射(reflect)在页面中。我在这里遗漏了什么吗?
请参阅下面的代码。
import React, { Component } from 'react';
import { createStore } from 'redux';
class ReduxDemo extends Component {
constructor(props) {
super(props);
this.initNukeAttack = this.initNukeAttack.bind(this);
this.store = null;
}
initNukeAttack() {
console.log("I am inside initNukeAttack");
this.store.dispatch({type:"GREEN-ATTACK", hero: "Hulk"});
}
render() {
let attackHero = "attack hero";
// step 2 -> reducer => require state and action
const reducer = function(state, action) {
if(action.type === "ATTACK") {
return action.hero;
}
if(action.type === "GREEN-ATTACK") {
return action.hero;
}
return {p:"peace"};
}
//Step 1
this.store = createStore(reducer, "PEACE");
//step 3 -> subscribe
this.store.subscribe(() => {
//console.log("Store is now", store.getState());
//console.log(store.getState());
attackHero = this.store.getState();
})
//step 4 -> dispatch action
this.store.dispatch({type:"ATTACK", hero: "Ironman"});
//this.store.dispatch({type:"GREEN-ATTACK", hero: "Hulk"});
return(
<div>
<div>{attackHero}</div>
<button onClick={this.initNukeAttack}>Initiate Green Attack</button>
</div>
);
}
}
export default ReduxDemo;
渲染的屏幕如下所示。
最佳答案
您好,首先我建议正确遵循带有 redux 的 React 和用于操作创建者的中间件。有丰富的可用资源。
不管怎样,你在渲染中调度了一个错误的 Action 。其次,为了更新变量,您需要 setState
来重新渲染组件。
这是您的工作代码:
class ReduxDemo extends Component {
constructor(props) {
super(props);
this.initNukeAttack = this.initNukeAttack.bind(this);
this.store = null;
this.state = {
attackHero: "IronMan"
};
}
initNukeAttack() {
console.log("I am inside initNukeAttack");
this.store.dispatch({ type: "GREEN-ATTACK", hero: "Hulk" });
}
render() {
// step 2 -> reducer => require state and action
const reducer = function(state = "ironman", action) {
if (action.type === "ATTACK") {
return action.hero;
}
if (action.type === "GREEN-ATTACK") {
return action.hero;
}
return state;
};
//Step 1
this.store = createStore(reducer, "PEACE");
//step 3 -> subscribe
this.store.subscribe(() => {
//console.log("Store is now", store.getState())
const attackHero = this.store.getState();
this.setState({
attackHero
})
});
//step 4 -> dispatch action
//this.store.dispatch({ type: "ATTACK", hero: "Ironman" });
// this.store.dispatch({type:"GREEN-ATTACK", hero: "Hulk"});
return (
<div>
<div>{this.state.attackHero}</div>
<button onClick={this.initNukeAttack}>Initiate Green Attack</button>
</div>
);
}
}
关于javascript - React - 变量未正确显示在页面中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52016369/