redux - just understand more about mapStateToProps

Commit

Mistake I made
I find PttPosts implementation component seems incorrect.

PttPosts.js
import React, {Component} from "react";
import {connect} from 'react-redux'
import {selectPttPost} from '../actions'

class PttPosts extends Component {
    renderPosts() {
        return this.props.pttPosts.map((post) => {
           return <div key={post.title}>
               ${post.title} / ${post.author} <button onClick={() => this.props.selectPttPost(post)} key={post.title}>Click</button>
           </div>
        });
    }

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

// incorrect
const mapStateToProps = (state) => {
    console.log("mapStateToProps", state)
    return state;
}

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

And then I realized “mapStateToProps” can put the attribute name used when render function was called.
Just like PttPostContent.js
import React, {Component} from "react";
import {connect} from 'react-redux'

const PttPostContent = ({pttPost}) => { // 2. So we can get data from attribute when redering
    if (!pttPost) {
        return <div />
    }

    return <div>
        <div>${pttPost.title}</div>
        <div>${pttPost.author}</div>
    </div>
}

const mapStateToProps = (state) => {
    console.log("mapStateToProps", state)
    return {pttPost: state.selectedPttPost} // 1. Because “pttPost” was put to props
}

export default connect(mapStateToProps)(PttPostContent)

沒有留言:

張貼留言

別名演算法 Alias Method

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