我正在尝试将reducers中的状态连接到react组件中的组件。
以下是reducer的代码位于reducer_books.js
:
export default function(){
return [
{title:'A'},
{title:'E'}
];
}
然后,我将它添加到index.js
中的联合收割机减速器:
import {combineReducers} from 'redux';
import BookReducer from './reducer_books';
const rootReducer= combineReducers({
books:BookReducer
});
export default rootReducer;
最后我尝试将其添加到父组件中:
import State from './reducer/index';
import { Provider } from 'react-redux';
ReactDOM.render(
<Provider store={State}>
<App />
</Provider>, document.getElementById('root'));
在目标组件中我有:
import React,{Component} from 'react';
import {connect} from 'react-redux';
class BookList extends Component{
renderList(){
return this.props.books.map((book)=>{
<li key={book.title}>{book.title}</li>
});
}
render(){
return(
<div>
<ul>
{this.renderList()}
</ul>
</div>);
}
}
function mapStateToProps(state){
return{
books:state.books
};
}
export default connect(mapStateToProps)(BookList);
不幸的是,它抱怨:
Warning: Failed prop type: Invalid prop `store` of type `function` supplied to `Provider`, expected `object`.
in Provider (at index.js:11)
Warning: Failed childContext type: Invalid child context `store` of type `function` supplied to `Provider`, expected `object`.
in Provider (at index.js:11)
Warning: Failed context type: Invalid context `store` of type `function` supplied to `Connect(BookList)`, expected `object`.
in Connect(BookList) (at App.js:35)
in div (at App.js:33)
in div (at App.js:32)
in App (at index.js:12)
in Provider (at index.js:11)
Uncaught TypeError: _this.store.getState is not a function
Error: Attempted to update component `Connect(BookList)` that has already been unmounted (or failed to mount)
答案 0 :(得分:9)
在你的例子中,我不知道你configure Store
的位置,我想你错过了这一步
import reducers from './reducer/index';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
const Store = createStore(reducers);
ReactDOM.render(
<Provider store={ Store }>
<App />
</Provider>, document.getElementById('root')
);