javascript - React - 变量未正确显示在页面中
问题描述
我有一个变量attackHero
,其初始值为 Ironman。它在页面上正确显示。单击按钮时,我通过 Redux 调度将其更改为 Hulk。但是这种变化并没有反映在页面中。我在这里错过了什么吗?
请看下面的代码。
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 来响应动作创建者。有丰富的资源可供使用。无论如何,您在渲染中调度了一个错误的操作。其次,为了更新您需要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>
);
}
}
推荐阅读
- mapstruct - 为所有其他映射注册映射
- ios - App Store Connect 操作错误:路径中缺少 CFBundleIdentifier
- android - webrtc 看不到远程视频但可以听到音频
- centos - 无法映射名称 UUID | 起搏器 | linux集群
- python - sympy 中的其他简化
- redirect - Identity Server 4 - 取消重定向到登录并返回 401
- node.js - shopify结账支付api上的404
- domain-driven-design - DDD - 执行需要了解多个聚合根的规则
- jquery - 检查输入值是否与 ids 值相同
- node.js - 将限制设置为最大行数