首页 > 解决方案 > 将 Redux 状态传递给子组件时遇到问题

问题描述

我是 Redux 的新手,我一直在使用 Redux 文档中第一个示例项目的代码。该示例不使用容器或具有单独的操作文件,所以我想我会从那里开始并尝试将它抽象一点。

该项目没有App组件,并且index.js文件看起来像这样开始:

import React from 'react'
import ReactDOM from 'react-dom'
import { createStore } from 'redux'
import Counter from './components/Counter'
import counter from './reducers'

const store = createStore(counter)
const rootEl = document.getElementById('root')

const render = () => ReactDOM.render(
  <Counter
    value={store.getState()}
    onIncrement={() => store.dispatch({ type: 'INCREMENT' })}
    onDecrement={() => store.dispatch({ type: 'DECREMENT' })}
  />,
  rootEl
)

render()
store.subscribe(render)

我首先更改了它,以便它安装了一个App组件:

...

import { Provider } from 'react-redux':

...

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

我已将Counter组件移动到App.js中,并尝试使用它mapStateToProps来引入初始状态(state = 0在减速器中设置为):

import React from 'react';
import Counter from '../components/Counter.js';
import { connect } from 'react-redux';

class App extends React.Component {

    render() {
        return(
            <div>
                <Counter value={value} />
            </div>
        );
    }
}

const mapStateToProps = (state) => {
    return { value: state.value };
}

export default connect(mapStateToProps)(App);

我正在尝试传递设置Counter在.valuemapStateToProps

使用上面的代码,我在以下位置收到错误<Counter value={value} />

'value' 未定义 no-undef

听起来很疯狂,我想也许我必须在函数内部初始化才能value使这项工作:constructorApp

constructor() {
    super(props);

    this.state = {
        value: 0
    }
}

这没有用,而且无论如何都没有意义,因为状态是在减速器中初始化的。

标签: reactjsreduxreact-redux

解决方案


它非常简单,您做对了,但您只需要在渲染方法中进行一些更改,以获得更新的值,您的问题将得到解决。

只需在您的 App 组件中进行这些更改即可。

import React, {Component} from 'react';
import Counter from '../components/Counter.js';
import { connect } from 'react-redux';

class App extends Component {

  render() {
    const {
      props: {
        value
      }
    } = this;
    return(
        <div>
            <Counter value={value} />
        </div>
    );
  }
}

你不需要initializeconstructor方法中赋值。


推荐阅读