【问题标题】:My reactJS app doesnt re renders when redux changes the state in store当 redux 更改商店中的状态时,我的反应 JS 应用程序不会重新呈现
【发布时间】:2019-05-11 13:55:16
【问题描述】:

我刚开始学习 Redux。 当我编写 store.subscribe(render) 时,我的应用程序编译没有错误,但没有任何显示。 我一直在关注一篇文章(https://medium.freecodecamp.org/understanding-redux-the-worlds-easiest-guide-to-beginning-redux-c695f45546f6),它很好地解释了redux,但订阅部分不起作用。 非常感谢这方面的任何帮助。

我尽我所能,我什至重建了应用程序,但没有运气。

index.js

./reducer/index.js

./store/index.js

App.js

【问题讨论】:

  • 你为什么使用 store.subscribe ?而不是使用像这样的提供者``` ,```
  • 我是 redux 新手,一直在关注这篇文章 >>>medium.freecodecamp.org/…
  • 请使用react-redux,使用redux和react时更简洁易懂且无副作用。你可以关注这篇文章:medium.freecodecamp.org/…
  • 我仍处于学习阶段,所以我想先坚持更简单的事情。请检查我的代码并告诉我哪里出错了:(
  • 好的,您能否提供 jsfiddle 示例而不仅仅是图像!?

标签: reactjs react-native redux react-redux reactive-programming


【解决方案1】:

首先,尝试将 App.js 的第 17 行从

<HelloWorld tech={this.state.tech}/>

到:

<HelloWorld tech={store.getState().tech}/>

否则,请尝试将构造函数放入您的 App 组件中:

constructor(props) {
    super(props);
    store.subscribe(() => {
      this.setState({
        tech: store.getState().tech
      });
    });
  }

【讨论】:

  • 非常感谢添加构造函数终于解决了我的问题。再次感谢您^_^
【解决方案2】:

您需要将提供程序添加到您的商店以订阅更改。 更多详情请查看此链接https://react-redux.js.org/api/provider

请找到商店的示例代码。

import React from 'react'
import ReactDOM from 'react-dom'
import { Provider } from 'react-redux'

import { App } from './App'
import createStore from './createReduxStore'

const store = createStore()

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
)

【讨论】:

  • 但是我关注的文章没有提到任何提供者或我遵循文章所教的所有内容。进展顺利,但后来我遇到了这个问题。当我编写 render() 时,我的应用程序出现了,但是当我编写 store.subscribe() 并且 DOM 也没有更新 store 中的新状态时它没有显示。
【解决方案3】:

你必须导入 createStore。

import { createStore } from 'redux';

然后你需要将 store 设为变量并传入 reducer。

const store = createStore(yourReducer);

那么你的 reducer 会是这个样子。

const initState = {

}

const yourReducer = (state = initState, action) => {
    return state;
}

export default yourReducer

【讨论】:

  • 嗯,这正是我所做的,状态变化我在 console.log 中验证了它唯一的问题是当状态变化时我的 DOM 没有重新呈现,当我用户 store.subscribe(渲染)在我的 index.js 文件中
猜你喜欢
  • 2018-04-09
  • 2016-06-25
  • 2017-05-31
  • 2018-09-01
  • 2020-10-19
  • 2021-12-28
  • 2014-09-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多