学习Redux和React,我遇到了一个问题,在哪里创建了存储,并通过react传递给了我的<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>组件,但这也可能是错误的。为了更好的衡量,这是我的应用程序组件。
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;发布于 2018-03-14 15:19:55
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。
发布于 2018-03-14 15:16:53
<Provider>“为放置在其下面的使用connect()的组件提供存储支柱。
您不能将<Provider>放在组件的呈现函数中并更改传递给它的道具。那时候已经太晚了。道具就是他们的样子。
这将发生在树中的这个组件之上,或者是另一个组件,或者是在您的ReactDOM.render调用期间。
https://stackoverflow.com/questions/49281336
复制相似问题