[英]Redux store not being passed to props on component
Learning Redux and React, and I'm having an issue where I have the store created, and passed over to my <Provider>
through react-redux, but I get an empty object when logging in the console. 在学习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;
I think the issue may lie with how I'm passing it to the <Provider>
component, but that also could be wrong. 我认为问题可能在于如何将其传递给<Provider>
组件,但这也可能是错误的。 Just for good measure, here is my App component. 出于很好的考虑,这是我的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;
<Provider>
"provides" the store prop to components placed below it that use connect()
. <Provider>
将存储道具“提供”给放置在其下方的使用connect()
。
You can't place the <Provider>
within a component's render function and change the props passed to it. 您不能将<Provider>
放置在组件的render函数中并更改传递给它的道具。 It's already too late at that point. 那时已经为时已晚。 The props are what they are. 道具就是它们。
That will happen above this component in the tree, either another component or during your ReactDOM.render
call. 这将发生在树中该组件之上,或者是另一个组件,或者发生在您的ReactDOM.render
调用期间。
The redux state does not automatically show up as props everywhere; redux状态不会自动显示为道具。 and rightfully so. 是这样。 If that is the case, the performance would be devastating unless you have custom shouldComponentUpdate
. 如果shouldComponentUpdate
这样,除非您有自定义的shouldComponentUpdate
否则性能将是毁灭性的。
What you need to use is connect
the redux state to your component. 您需要使用的是connect
redux状态connect
到您的组件。 For your example, it'll be something like: 以您的示例为例:
import { connect } from 'react-redux';
...
// Replace last line with this:
export default connect(
state => ({ tasks: state.tasks }),
null,
)(App);
Now, this.props.tasks
will be the tasks
in your redux state. 现在, this.props.tasks
将成为您的redux状态下的tasks
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.