【问题标题】:Changing state but not rerendering react redux改变状态但不重新渲染 react redux
【发布时间】:2018-12-31 14:11:13
【问题描述】:

我一直在访问 store 来更改状态,我什至可以在控制台中看到更改,但是 ui 没有重新渲染。 Here 是我的代码的存储库(它非常小而且基本)。 为什么我的 ui 没有重新渲染?

https://github.com/shanemmay/test-3

【问题讨论】:

  • 你能把你代码的相关部分贴在这里吗?
  • 您必须将组件连接到商店,以便商店更改触发重新渲染。如果它们未连接,则它们不会在商店更改时重新渲染,因此不会反映新的商店值。

标签: reactjs redux react-redux state store


【解决方案1】:

在您的 index.js 中,您需要更改将 store 提供给 App 组件的方式。应该是这样的。

import {Provider} from 'react-redux'

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

然后在您的 App.js 中,您需要将状态映射到道具,然后显示该道具的数字。最重要的是,您必须使用 connect 将您的 react 组件连接到 redux 存储。以下是您需要修改 App.js 的方法

 import React, { Component } from 'react';
 import {connect} from 'react-redux'


 class App extends Component {
   render() {
     return (
       <div>
         <h1>{this.props.number}</h1>
         <button onClick={
           () =>
           {
             this.props.dispatch({type:'+'});
           }
         }> + </button>
       </div>
     );
   }
 }

 const mapStateToProps = state => ({
   number: state
 })

 export default connect(mapStateToProps)(App);

请务必通过https://redux.js.org/basics/usage-with-react 获得更好的了解。

【讨论】:

    【解决方案2】:

    您的应用需要使用 madhu bhat 所说的提供者与 redux 框架连接。

    你必须遵循 redux 架构,基本的了解会非常简单地解决这个问题。

    基本流程

    访问我的仓库中的同类示例

    https://github.com/zural/react-redux-simple-counter/tree/master

    这将使您了解 redux 流程和反应状态。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-20
      • 2017-03-26
      • 1970-01-01
      • 2019-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-13
      相关资源
      最近更新 更多