我正在尝试弄清楚如何将 Redux 存储状态从 Redux 拉入我的组件中。我已经连接了 mapStateToProps
和 connect
。但是,当我单击 App
组件中的按钮时,this.props
中没有我的 Redux 值。
// React and Redux Const
const { Component } = React;
const { render } = ReactDOM;
const { Provider, connect } = ReactRedux;
const {createStore, combineReducers, bindActionCreators } = Redux;
function tweetReducer(state=[],action) {
if(action.type === 'ADD_TWEET') {
return state.concat({ id: Date.now(), tweet: action.payload})
} else {
return state;
}
}
const rootReducer = combineReducers ({
state: (state = {}) => state,
tweets: tweetReducer
});
class App extends Component{
buttonClicked() {
store.dispatch({type: 'ADD_TWEET', payload: 'This is my first
tweet!'});
console.log(this.props)
}
render() {
return (
<div>
<h5>Hello from App</h5>
<button onClick={this.buttonClicked.bind(this)}>Button</button>
<div>-------------------</div>
<Display />
</div>
)
}
}
class Display extends Component {
render() {
return (
<div>
<h3>Tweets:</h3>
{this.props.tweets}
</div>
)
}
}
function mapStateToProps(state) {
console.log('mapping state to props')
return {
tweets: state.tweets
}
}
let store = createStore(rootReducer)
render (
<Provider store={store}>
<App />
</Provider>
, document.querySelector('#app')
);
connect(mapStateToProps)(App)
console.log(store.getState());
最佳答案
看起来您遇到了一些问题。
首先,了解 connect()(MyComponent)
会有所帮助。返回一个“包裹”“真实”组件的新组件。在您的示例中,您正在调用 connect()
在渲染 <App />
后,和您实际上并没有保存和使用 connect()
生成的组件。你需要的是这样的:
let store = createStore(rootReducer)
const ConnectedApp = connect(mapStateToProps)(App);
render(
<Provider store={store}>
<ConnectedApp />
</Provider>
, document.querySelector('#app')
);
其次,连接组件的部分要点是它实际上不应该直接引用存储。 connect()
可以采用第二个参数,称为 mapDispatchToProps
。如果您不提供mapDispatch
参数,它会自动给你的组件 this.props.dispatch
。因此,您的应用程序组件应该如下所示:
class App extends Component{
buttonClicked(){
this.props.dispatch({type: 'ADD_TWEET', payload: 'This is my first tweet!'});
console.log(this.props)
}
这应该足以让 App 组件从 Redux 接收数据并调度操作。
关于reactjs - 组件中的 Redux 状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43900836/