redux - fetch user for each article

Declare UserHeader component
src/components/UserHeader.js
class UserHeader extends Component {

    componentDidMount() {
        this.props.fetchUser(this.props.userId)
    }

    render() {
        const user = this.props.users.find(user => user.id === this.props.userId);
        console.log("user", user);

        return <div>{user?.name}</div>
    }
}

const mapStateToProps = (state) => {
    return {users: state.users}
}

export default connect(mapStateToProps, {fetchUser})(UserHeader)

Add to PttPosts.js
src/components/PttPosts.js
import React, {Component} from "react";
import {connect} from 'react-redux'
import {fetchPosts, selectPttPost} from "../actions";
import UserHeader from "./UserHeader";


class PttPosts extends Component {
    componentDidMount() {
        this.props.fetchPosts()
    }

    renderList() {
        if (this.props.postList) {
            return this.props.postList.map((post) => {
                return <div key={post.id}>
                    <div key={post.id}><a onClick={() => this.props.selectPttPost(post)}>Title:{post.title}</a></div>
                    <UserHeader userId={post.userId} />
                </div>
            });
        } else {
            return 'Loading...'
        }
    };

    render() {
        return <div>{this.renderList()}</div>
    }
}

const mapStateToProps = (state) => {
    return {postList: state.fetchPosts};
}

export default connect(mapStateToProps, { fetchPosts, selectPttPost })(PttPosts)

Define action creator, put action 
src/actions/index.js
export const fetchUser = (userId) => async dispatch => {
    const response = await jsonPlaceholder.get(`/users/${userId}`)

    dispatch({type:'FETCH_USER', payload: response.data})
}

Add usersReducer and put to combineReducer
export const usersReducer = (state = [], action) => {
    if (action.type === 'FETCH_USER') {
        return [...state, action.payload]; // add payload to existing state
    }

    return state;
}

export default combineReducers({
    selectedPttPost: selectedPttPostReducer,
    fetchPosts: fetchPostReducer,
    users: usersReducer
})

Show page

Note
  1. Put action payload to state array, it causes many array elements are passed between different codes
  2. If not putting action payload to state array, UserHeader will keep showing the latest result



沒有留言:

張貼留言

別名演算法 Alias Method

 題目 每個伺服器支援不同的 TPM (transaction per minute) 當 request 來的時候, 系統需要馬上根據 TPM 的能力隨機找到一個適合的 server. 雖然稱為 "隨機", 但還是需要有 TPM 作為權重. 解法 別名演算法...