我想使用Posts组件显示数据,但是无法显示出来
AsyncApp.js
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import {
fetchPostsIfNeeded
} from '../actions'
import Posts from '../components/Posts'
class AsyncApp extends Component {
constructor(props) {
super(props)
this.handleChange = this.handleChange.bind(this)
}
componentDidMount() {
var o1 = { a: 1, b: 2 };
var o2 = { c: 3 };
var obj = Object.assign({}, o1, o2);
console.log('obj =', obj);
const { dispatch, selectedSubreddit } = this.props;
}
componentDidUpdate(prevProps) {
//
}
handleChange(nextSubreddit) {
console.log('nextSubreddit =', nextSubreddit)
this.props.dispatch(fetchPostsIfNeeded(nextSubreddit))
}
render() {
const { selectedSubreddit, posts, isFetching, lastUpdated } = this.props
return (
<div>
<button
onClick={() => this.handleChange('feng')}
>
点击
</button>
{posts.length > 0 &&
<div style={{ opacity: isFetching ? 0.5 : 1 }}>
<Posts posts={posts} />
</div>}
</div>
)
}
}
function mapStateToProps(state) {
const { selectedSubreddit, postsBySubreddit } = state
const {
isFetching,
lastUpdated,
items: posts
} = postsBySubreddit[selectedSubreddit] || {
isFetching: true,
items: []
}
return {
selectedSubreddit,
posts,
isFetching,
lastUpdated
}
}
export default connect(mapStateToProps)(AsyncApp)
actions.js
import fetch from 'cross-fetch'
export const REQUEST_POSTS = 'REQUEST_POSTS'
export const RECEIVE_POSTS = 'RECEIVE_POSTS'
export function fetchPostsIfNeeded(subreddit) {
return (dispatch, getState) => {
if (shouldFetchPosts(getState(), subreddit)) {
return dispatch(fetchPosts(subreddit))
}
}
}
function shouldFetchPosts(state, subreddit) {
const posts = state.postsBySubreddit[subreddit]
if (!posts) {
return true
} else if (posts.isFetching) {
return false
} else {
return posts.didInvalidate
}
}
//
function fetchPosts(subreddit) {
return dispatch => {
dispatch(requestPosts(subreddit))
return fetch(`http://tianjinshuxie.net/page/tasks.php?query=tasks&uid=100`)
.then(
response => response.json()
)
.then(
json => {
//console.log(`json =`, json)
dispatch(receivePosts(subreddit, json))
}
)
}
}
function requestPosts(subreddit) {
return {
type: REQUEST_POSTS,
subreddit
}
}
function receivePosts(subreddit, json) {
console.log(`json =`, json)
return {
type: RECEIVE_POSTS,
subreddit,
//posts: json.data.children.map(child => child.data),
posts: json.map(child => child),
receivedAt: Date.now()
}
}
Posts.js
import React, { Component } from 'react'
import PropTypes from 'prop-types'
export default class Posts extends Component {
render() {
return (
<ul>
{this.props.posts.map((post, i) => <li key={i}>{post.title}</li>)}
</ul>
)
}
}
你是不是少写了
reducer
。你的组件需要使用
connect
高阶函数将redux
的state
通过props
传入到Post
组件中。