我试图测试我的React“supersquadapp”并得到以下错误.
未捕获错误:无法在“Connect(CharacterList)”的上下文或道具中找到“store”.将根组件包装在a中,或者将“store”显式传递为“Connect(CharacterList)”的prop.
characterlist.js
import React,{ Component } from 'react'; import { connect } from 'react-redux'; class CharacterList extends Component { render() { console.log('this.props',this.props); return ( <div> <h4>characters</h4> </div> ) } } function mapStateToProps(state) { return { characters: state.characters } } export default connect(mapStateToProps,null)(CharacterList);
app.js
import React,{Component} from 'react'; import CharacterList from './CharacterList'; class App extends Component { render() { return ( <div> <h2>SUPER SQUAD</h2> <CharacterList /> </div> ) } } export default App;
index.js
import React from 'react'; import ReactDOM from 'react-dom'; import App from './Components/App'; import { createStore } from 'redux'; import { Provider } from 'react-redux'; import rootReducers from './reducers'; import { addCharacterById } from './actions'; const store = createStore(rootReducers); console.log(store.getState()); store.subscribe(() => console.log('store',store.getState())) store.dispatch(addCharacterById(3)); ReactDOM.render( <Provider> <App /> </Provider>,document.getElementById('root') )
character.js(在reducers文件夹中)
import characters_json from '../Data/characters.json'; import { ADD_CHARACTER } from '../actions'; function characters(state = characters_json,action) { switch(action.type) { case ADD_CHARACTER: let characters = state.filter(item => item.id !== action.id); return characters; default: return state; } } export default characters;
heroes.js(redurs文件夹)
import { ADD_CHARACTER } from '../actions'; import {createCharacter} from './helper'; function heroes(state = [],action) { switch(action.type) { case ADD_CHARACTER: let heroes = [...state,createCharacter(action.id)]; return heroes; default: return state; } } export default heroes;
helper.js(redurs文件夹)
import characters_json from '../Data/characters.json'; export function createCharacter(id) { let character = characters_json.find(c => c.id === id); return character; }
index.js(redurs文件夹)
import { combineReducers } from 'redux'; import characters from './characters_reducer'; import heroes from './heroes_reducer'; const rootReducer = combineReducers({ characters,heroes }) export default rootReducer;
index.js(动作文件夹)
export const ADD_CHARACTER = 'ADD_CHARACTER'; export function addCharacterById(id) { const action = { type:ADD_CHARACTER,id } return action; }
组件中出现上述错误:
在Connect(CharacterList)中(在App.js:9)
在div(在App.js:7)
在App中(在index.js:19)
在提供者(在index.js:18)
请帮我…?
解决方法
您必须将商店实例传递给Provider …
ReactDOM.render( <Provider store={store}> <App /> </Provider>,document.getElementById('root') )