javascript - 组件没有完全渲染并且没有随着状态的变化而变化
问题描述
我正在尝试实现一个基本的 React-Redux 计数器应用程序,但由于某种原因它没有完全渲染,正常的 html 部分正在工作,但是渲染函数中的this.store.getState() 正在获取值并且不是渲染。我试图找到调试它我发现的第一件事是当我尝试 console.log(this.store.getState()) 它返回未定义和我发现的第二件事是我没有使用store.subscribe重新渲染每次状态更改时的页面,我确定问题与它有关,但是当我们使用类渲染视图时如何包含store.subscribe ?
这是包含类 Counter的App.js代码
import React from 'react';
import {createStore} from 'redux'
class Counter extends React.Component{
constructor(props){
super(props);
this.store=createStore(this.counterReducer);
// this.store.subscribe(render);
}
counterReducer = (state=0,action) =>{
switch(action.type){
case 'INCREMENT':
return state+1;
case 'DECREMENT':
return state-1;
}
}
counter = (props) =>{
return(
<div>
<h1>Value : {props.value}</h1>
<button onClick={props.OnIncrement}>+</button>
<button onClick={props.OnDecrement}>-</button>
</div>
)
}
render(){
console.log(this.store.getState())
return (
<div>
<h1>Counter</h1>
<this.counter value={this.store.getState()} OnIncrement={() => {
this.store.dispatch({
type:'INCREMENT'
})
}} OnDecrement={() => {
this.store.dispatch({
type:'DECREMENT'
})
}
}/>
</div>
);
}
}
export default Counter;
这是 index.js 的代码
import React from 'react';
import ReactDOM from 'react-dom';
import Counter from './App';
ReactDOM.render(<Counter />, document.getElementById('root'));
解决方案
这是一个使用 useReducer 直接反应的解决方案。
import React, {useReducer} from 'react';
const counterReducer = (state,action) =>{
switch(action.type){
case 'INCREMENT':
return state+1;
case 'DECREMENT':
return state-1;
}
return state;
}
const CounterButton = (props) =>{
return(
<div>
<h1>Value : {props.value}</h1>
<button onClick={props.OnIncrement}>+</button>
<button onClick={props.OnDecrement}>-</button>
</div>
)
}
const Counter = () =>{
const [state, dispatch] = useReducer(counterReducer, 0);
return (
<div>
<h1>Counter</h1>
<CounterButton value={state} OnIncrement={() => {
dispatch({
type:'INCREMENT'
})
}} OnDecrement={() => {
dispatch({
type:'DECREMENT'
})
}
}/>
</div>
);
}
export default Counter;
推荐阅读
- c++ - 如何将 wxDataViewListCtrl 更改为适合 wxPanel
- python - Pyinstaller - 如何包含图像文件夹?
- c# - “生成方法”建议不支持重载方法
- json - 读取 JSON 并解析内容并在 Scala 中显示结果
- python - 如何使用这个等式在 Python 中计算样本量?
- python - 如何绘制多个条形图?
- sql - postgres如何向jsonb数组中的dicts添加一个键
- javascript - 更改单选按钮时如何清除表单
- python - python脚本可以自己删除文件吗?
- c++ - 使用 Vector 和 QDate 优化 C++ 中的 if 语句