this.props.dispatch(fetchPostsIfNeeded(nextSubreddit))
中的this.props
有什么作用?去掉可不可以?
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import {
fetchPostsIfNeeded
} from '../actions'
import Async from '../components/Async'
class AsyncApp extends Component {
constructor(props) {
super(props)
this.handleClick = this.handleClick.bind(this, 'reactjs')
this.state = {abc:'人生的无限'}
}
handleClick(nextSubreddit) {
// 点击按钮传参 reactjs
this.props.dispatch(fetchPostsIfNeeded(nextSubreddit))
alert(nextSubreddit);
}
render() {
const { selectedSubreddit, posts, isFetching, lastUpdated } = this.props
return(
<div>
<Async val={this.state.abc}/>
<h1>isFetching=={isFetching.toLocaleString()}</h1>
<button onClick={this.handleClick}>点击</button>
</div>
)
}
}
/*
{
selectedSubreddit: 'frontend',
postsBySubreddit: {
frontend: {
isFetching: true,
didInvalidate: false,
items: []
},
reactjs: {
isFetching: false,
didInvalidate: false,
lastUpdated: 1439478405547,
items: [ 42, 100 ]
}
}
}
*/
/*
function mapStateToProps(state) {
const { postsBySubreddit, selectedSubreddit } = state
const {
isFetching,
items: posts
} = {
isFetching: true,
items: []
}
return {
posts,
isFetching
}
}
*/
/*
function mapStateToProps(state) {
const { selectedSubreddit, postsBySubreddit } = state
const {
isFetching,
lastUpdated,
items: posts
} = postsBySubreddit[selectedSubreddit] || {
isFetching: true,
items: []
}
return {
selectedSubreddit,
posts,
isFetching,
lastUpdated
}
}
*/
// 初始化 state
function mapStateToProps(state) {
var selectedSubreddit = state.selectedSubreddit,
postsBySubreddit = state.postsBySubreddit;
var _ref = postsBySubreddit[selectedSubreddit] || {
isFetching: true,
items: []
},
isFetching = _ref.isFetching,
lastUpdated = _ref.lastUpdated,
posts = _ref.items;
return {
selectedSubreddit: selectedSubreddit,
posts: posts,
isFetching: isFetching,
lastUpdated: lastUpdated
};
}
export default connect(mapStateToProps)(AsyncApp)
this.props是React组件的属性对象,每一个React组件都有这个属性的。Redux通过connect方法,将store的dispatch方法保存到组件的props中,这样在组件内部,就可以通过this.props.dispatch的方式,发送action了。