鍍金池/ 問(wèn)答/HTML/ 使用redux為什么無(wú)法獲取到posts這個(gè)值

使用redux為什么無(wú)法獲取到posts這個(gè)值

如何修改下面的函數(shù),才能獲取到值?

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 = { b: 5 };

        var obj = Object.assign({}, o1, o2);
        console.log('obj =', obj);

    }

    componentDidUpdate(prevProps) {
        const { dispatch, selectedSubreddit } = this.props
        console.log('selectedSubredditUpdate =', selectedSubreddit)
    }

    handleChange(nextSubreddit) {
        console.log('nextSubreddit =', nextSubreddit)
        this.props.dispatch(fetchPostsIfNeeded(nextSubreddit))
    }


    render() {
        const { selectedSubreddit, posts, isFetching, lastUpdated } = this.props

        console.log('posts =', posts)
        console.log('selectedSubreddit =', selectedSubreddit)
        return (
            <div>

                <button
                    onClick={() => this.handleChange('identify')}
                >
                    點(diǎn)擊
                </button>

                {posts.length > 0 &&
                <div style={{ opacity: isFetching ? 0.5 : 1 }}>
                    <Posts posts={posts} />
                </div>}

            </div>
        )
    }
}

AsyncApp.propTypes = {
    selectedSubreddit: PropTypes.string.isRequired,
    posts: PropTypes.array.isRequired,
    isFetching: PropTypes.bool.isRequired,
    lastUpdated: PropTypes.number,
    dispatch: PropTypes.func.isRequired
}

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'

// 是為了后面在 reducer中可以匹配到對(duì)應(yīng)到 type
export const REQUEST_POSTS = 'REQUEST_POSTS'
export const RECEIVE_POSTS = 'RECEIVE_POSTS'

/*
 * action 創(chuàng)建函數(shù)
 */


// 暴露出這個(gè)方法,其他地方可以調(diào)用這個(gè)方法去觸發(fā)這個(gè) action
// 接收到添加的請(qǐng)求,去找 reducers 實(shí)現(xiàn)
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()
    }
}

reducers.js

import { combineReducers } from 'redux'
import {
    REQUEST_POSTS,
    RECEIVE_POSTS
} from './actions'

function posts(
    state = {
        isFetching: false,
        didInvalidate: false,
        items: []
    },
    action
) {
    switch (action.type) {

        case REQUEST_POSTS:
            return Object.assign({}, state, {
                isFetching: true,
                didInvalidate: false
            })
        case RECEIVE_POSTS:
            return Object.assign({}, state, {
                isFetching: false,
                didInvalidate: false,
                items: action.posts,
                lastUpdated: action.receivedAt
            })
        default:
            return state
    }
}

function postsBySubreddit(state = {}, action) {
    switch (action.type) {
        case RECEIVE_POSTS:
        case REQUEST_POSTS:
            let objectPost = Object.assign({}, state, {
                [action.subreddit]: posts(state[action.subreddit], action)
            })

            console.log('objectPost =', objectPost)

            return objectPost;
        default:
            return state
    }
}

// 傳遞過(guò)來(lái) type: ADD_TODO和text 然后調(diào)用 visibilityFilter和todos 兩個(gè)方法
const rootReducer = combineReducers({
    postsBySubreddit
})

export default rootReducer

configureStore.js

import { createStore, applyMiddleware } from 'redux'
import thunkMiddleware from 'redux-thunk'
import { createLogger } from 'redux-logger'
import rootReducer from './reducers'

const loggerMiddleware = createLogger()

export default function configureStore(preloadedState) {
    return createStore(
        rootReducer,
        preloadedState,
        applyMiddleware(
            thunkMiddleware,
            loggerMiddleware
        )
    )
}

Posts.js

import React, { Component } from 'react'
import PropTypes from 'prop-types'

export default class Posts extends Component {
    render() {

        console.log('this.props.posts =', this.props.posts)
        return (
            <ul>
                {this.props.posts.map((post, i) => <li key={i}>{post.title}</li>)}
            </ul>
        )
    }
}

Posts.propTypes = {
    posts: PropTypes.array.isRequired
}

圖片描述

回答
編輯回答
舊螢火

reducers.js 處理后的數(shù)據(jù)無(wú)法返回

2017年11月5日 15:16