【问题标题】:React Redux (within a single file) not calling render() after store changedReact Redux(在单个文件中)在存储更改后不调用 render()
【发布时间】:2020-01-03 02:49:12
【问题描述】:

我正在尝试创建一个 React Redux 文件的简单示例,以演示从 API 检索数据后的更改。 reducer 肯定会创建一个新的状态来返回,但 render() 没有被调用。 render() 是否仅在 Provider 标签内的子组件中调用; IE。不会调用定义Provider的组件的render()?

任何帮助将不胜感激,已经查看了几个小时的文档.. :-(

import React from 'react';
import axios from 'axios';
import { createStore } from 'redux';
import { Provider } from 'react-redux';

import './App.css';

const DELAY = 10000;
const initialState = { count: 0, fact: "" };


class App extends React.Component
{
  reducer( state = initialState, action )
  {
    console.log( 'reducer', state, action );
    let newState = {};

    switch( action.type )
    {
      case "UPDATE":
        newState = { count: state.count + 1, fact: action.fact };
        console.log( 'newState', newState );
        break;

      default:
        newState = {...state};
    }

    return newState;
  }

  store = createStore( this.reducer );

  async getNumberFact( number )
  {
    const response = await axios.get(`http://numbersapi.com/${number}/math`);
    return response;
  }

  componentDidMount()
  {
    setInterval( () =>
    {
      this.getNumberFact( this.store.getState().count )
      .then( (response) =>
      {
        this.store.dispatch( { type: "UPDATE", fact: response.data } );
      } )
      .catch( (error) =>
      {
        console.log( `Totally got this error: ${error}`);
      } );

    }, DELAY );
  }

  render()
  {
    return(
      <Provider store={this.store}>
        <div>
          {console.log( this.store.getState() )}
          <p>{this.store.getState().count}</p>
          <p>{this.store.getState().fact}</p>
        </div>
      </Provider>
    );
  }
}

export default App;

【问题讨论】:

标签: javascript reactjs asynchronous redux


【解决方案1】:

当组件的状态或道具发生变化时会发生更新。您的 render 函数两者都没有。我希望{this.store.getState().count} 能够在挂载上运行,然后再也不会。您的组件没有道具,也没有对this.state 的引用。引用this.store 和组件本地状态不是一回事。它是 redux 存储——在一个非常规的地方,我可能会添加——并且组件不直接响应 redux 存储。这就是 mapStateToProps 这样的方法的用途。

https://reactjs.org/docs/react-component.html#updating

https://react-redux.js.org/using-react-redux/connect-mapstate

【讨论】:

    猜你喜欢
    • 2021-02-24
    • 2018-01-06
    • 1970-01-01
    • 2021-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-12
    相关资源
    最近更新 更多