Redux商店未被传递给组件

时间:2018-03-14 15:11:45

标签: javascript reactjs redux

学习Redux和React,我遇到了创建商店的问题,并通过react-redux传递给我的<Provider>,但是在登录控制台时我得到一个空对象

import {  createStore,  applyMiddleware } from 'redux';
import  logger from 'redux-logger';
import  thunk from 'redux-thunk';

import uuid from 'uuid';


var defaultState = {
  tasks: [{
    key: uuid.v4(),
    name: 'learn Redux',
    description: 'Learn how to create a completely statefully managed application.',
    priority: 1,
    notes: [{
      key: uuid.v4(),
      content: 'Creation of the store is paramount. One must import {createStore, applyMiddleware from redux package}, then define the root reducer, and create the store with applymiddleware, and then export the store.'
    }],
  }, ]
};

var root = (state = defaultState, action) => {
  return state;
};

var store = createStore(root, applyMiddleware(thunk,logger));

export default store;

我认为问题可能在于我如何将其传递给<Provider>组件,但这也可能是错误的。好的方法,这是我的App组件。

import React, { Component } from 'react';
import './App.css';
import store from './store/createStore';
import { Provider } from 'react-redux';


class App extends Component {
  render() {
    console.log(this.props);
    // let tasks = this.props.tasks.map(x => {
    //   return <p>{x.name}</p>
    // })
    return (
      <Provider store={store}>
        <h1>Nothing to see here.</h1>
      </Provider>
    );
  }
}

export default App;

2 个答案:

答案 0 :(得分:2)

<Provider>&#34;提供&#34;商店支持使用connect()放置在其下方的组件。

您无法将<Provider>置于组件的渲染功能中,并更改传递给它的道具。那时候已经太晚了。道具就是它们。

这将发生在树中的此组件上方,或者是另一个组件或ReactDOM.render调用期间。

答案 1 :(得分:0)

redux状态不会自动显示为各处的道具;这是理所当然的。如果是这种情况,除非您有自定义shouldComponentUpdate,否则性能将是毁灭性的。

您需要使用的是connect组件的redux状态。对于您的示例,它将类似于:

import { connect } from 'react-redux';

...

// Replace last line with this:
export default connect(
  state => ({ tasks: state.tasks }),
  null,
)(App);

现在,this.props.tasks将成为您的redux状态中的tasks

相关问题