我现在想在React和Redux中学习时,想做一个计数器组件。 所以我想更改评估输入,然后单击解析输入,最后将解析显示为component2。但是,当我单击时,在reducer和action中更改了解析(我已经主持了解析),但是没有更改component2,为什么?我的英语不好,谢谢...
这是我的完整代码:
actions.js
export function DO_COUNT(resolve) {
return {
type: 'DO_COUNT',
payload: resolve
}
}
reducer.js
import actions from '../actions'
export default (state = { resolve: 0 }, actions) => {
switch (actions.type) {
case 'DO_COUNT':
console.log({
...state,
resolve: actions.payload
})
return {
...state,
resolve: actions.payload
}
break
default:
return state
}
}
store.js
import { createStore } from 'redux'
import reducers from '../reducers'
import { composeWithDevTools } from 'redux-devtools-extension'
const store = createStore(reducers, composeWithDevTools())
export default store
我的component1:Counter.js
import React, { Component } from 'react'
import styleObj from './style.less'
import store from '../../store'
import { DO_COUNT, CHANGE_EVAL } from '../../actions'
export default class Counter extends Component {
constructor(props) {
super(props)
this.state = {
num1: 0,
num2: 0,
myEval: '+'
}
}
changeEval = e => {
this.setState({
myEval: e.target.value
})
}
changeNum1 = e => {
// let _target = e.target.dataset.target
let value = e.target.value
this.setState(
{
num1: value
},
() => {
console.log(this.state)
}
)
}
changeNum2 = e => {
// let _target = e.target.dataset.target
let value = e.target.value
this.setState(
{
num2: value
},
() => {
console.log(this.state)
}
)
}
doCount = () => {
let resolve = eval(
[this.state.num1, this.state.num2].join(this.state.myEval)
)
store.dispatch(DO_COUNT(resolve))
}
render() {
return (
<div className={styleObj.counterBox}>
<input type="number" onInput={this.changeNum1} data-target="num1" />
<select onChange={this.changeEval}>
<option defaultValue="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
<input type="number" onInput={this.changeNum2} data-target="num2" />
<input type="button" value="=" onClick={this.doCount} />
</div>
)
}
}
我的component2:Container.js
import React, { Component } from 'react'
import styleObj from './style.less'
import store from '../../store'
export default class Container extends Component {
constructor(props) {
super(props)
}
render() {
return <h1 className={styleObj.content}>{store.getState().resolve}</h1>
}
}
和图片:
答案 0 :(得分:0)
您应该使用react-redux。
问题是商店的状态更改时未通知您的Container
组件。您可以通过进入生命周期方法并设置状态来手动完成此操作,但这是react-redux
已经做过的(以更优化的方式)。