首页 > 解决方案 > 组件没有完全渲染并且没有随着状态的变化而变化

问题描述

我正在尝试实现一个基本的 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'));

标签: javascriptreactjsredux

解决方案


这是一个使用 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;

推荐阅读