我在这个页面上看到了http://blog.tylerbuchea.com/super-simple-react-redux-application-example/并尝试重复它:
import React from 'react';
import ReactDom from 'React-dom';
import {Redux,bindActionCreators,combineReducers,
createStore,applyMiddleware} from 'redux';
import { connect, Provider} from 'react-redux';
import thunk from 'redux-thunk';
// actions.js
const activateGeod = geod => ({
type: 'ACTIVATE_GEOD',
geod,
});
const closeGeod = () => ({
type: 'CLOSE_GEOD',
});
// reducers.js
const geod = (state = {}, action) => {
switch (action.type) {
case 'ACTIVATE_GEOD':
return action.geod;
case 'CLOSE_GEOD':
return {};
default:
return state;
}
};
const reducers = combineReducers({
geod,
});
const customMiddleWare = store => next => action => {
console.log("Middleware triggered:", action);
next(action);
};
function configureStore(initialState = {}) {
const store = createStore(
reducers,
initialState,
//applyMiddleware(thunk)
applyMiddleware(customMiddleWare)
)
return store;
};
const store = configureStore();
store.subscribe(() => console.log(store.getState()))
// App.js
class App extends React.Component {
render() {
debugger
return (
<div>
PAGE:
<h1>{this.props.geod.title || 'Hello World!'}</h1>
{this.props.geod.title ?
<button onClick={this.props.closeGeod}>
Exit Geod
</button> :
<button onClick={() =>
this.props.activateGeod({ title: 'I am a geo dude!' })}>
Click Me!
</button>
}
</div>
);
}
}
// AppContainer.js
const mapStateToProps = (state, ownProps) => ({
geod: state.geod,
});
const mapDispatchToProps = {
activateGeod,
closeGeod,
};
const AppContainer = connect(
mapStateToProps,
mapDispatchToProps
)(App);
ReactDom.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('wr')
);
但我收到了错误:
无法读取未定义的属性'title'
有可能为state.props设置默认道具吗?
答案 0 :(得分:2)
由于您没有渲染连接组件而导致this.props.geod
未定义的原因。您已将应用程序组件与redux store(如
const AppContainer = connect(
mapStateToProps,
mapDispatchToProps
)(App);
因此,您的关联组件存储在AppContainer
中,但您正在渲染App
ReactDom.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('wr')
);
App
未与商店相关联的位置。所以解决方案就是像这样呈现连接组件
ReactDom.render(
<Provider store={store}>
<AppContainer />
</Provider>,
document.getElementById('wr')
);