繁体   English   中英

如何在 redux 中改变状态?

[英]How changing the state in redux?

我是 redux 的新手,并试图在我的应用程序中实现 redux。 我有一个 index.js 将数据渲染到屏幕,我有另一个组件应用程序。 我添加了“应用程序”功能作为 phonebookreducer 的订阅者。 我在 App 函数中添加了一些 console.log 来检查它是否在 phonebookreducer 中更新状态后被调用。 该函数被调用,但更新的状态未呈现在屏幕上。 但是当我从 index.js 添加渲染函数作为订阅者时,更新的状态就会被渲染。

我的问题是我确定当 phonebookreducer 的状态发生变化时,它正在调用 App 函数,但为什么更新的状态没有呈现在屏幕上。 react 中的“useState”也使用相同的机制,但是当状态从 useState 函数更改时,更新的状态正在呈现。

如果添加根渲染函数(index.js->render)作为订阅者是唯一的解决方案。 那么是否需要重新渲染我的整个 DOM 以更改与简单组件相对应的状态?

我的 index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';

import {PBReducer} from './reducers/phonebookreducer' // redux-reducer function

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

我的组件 App.js

import React from 'react';
import logo from './logo.svg';
import './App.css';
import AddContact from './components/addContact'
import DisplayContact from './components/displayContacts'
import {PBReducer} from './reducers/phonebookreducer' // redux-reducer function

function App(props) {
  return (
    <div>
      <AddContact store={props.store}/>
      <DisplayContact store={props.store}/>

      </div>
  );
}

PBReducer.subscribe(App);
export default App;

我的 phonebookreducer.js

import { createStore } from 'redux'


const reducer=(state=[],action)=>
{
if (action.type==="NEW")
    {
      return state.concat(action.data);
    }
   return state;

}

export const PBReducer=createStore(reducer);

这是一个奇怪的技巧: PBReducer.subscribe(render) ,实际上它确实有效,因为每次状态改变时你都会调用ReactDOM.render

但这不是以 React 方式进行状态更新,而是每次都进行初始挂载( ReactDOM.render用于进行初始挂载)。

因此,解决方案是使用react-redux和函数connectmapStateToProps

看起来是这样的:

import { Provider } from 'react-redux'

function App(props) {
  return (
    <Provider store={store}/> // there's one single store in a React app, so name it 'store' (it was 'PBreducer' in your question)
      <div>
        <AddContact/>
        <DisplayContact/>
      </div>
    </Provider>
  );
}

ReactDOM.render(<App/>, document.getElementById('root'))


/* an example component connected to the store : */

import { connect } from 'react-redux'

const mapStateToProps = (state) => ({
  items: state // the prop 'item' will be available in the component, it will match the store
})

class AddContact extends React.Component {
   /* ... */
  render() {
    return (
      /* ... use this.props.items here for example ... */
    )
  }
}

export default connect(mapStateToProps)(AddContact) // this line makes AddContact being synced with the store

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM