redux - select post


import action creator to component
pass action creator to connect
print this.props in render function -> after pass to connect function, actionCreator function will be added to this.props
add arrow function to button onClick event
call action creator in arrow function: this.props.selectSong(song) => state will be changed after click button
print state in mapStateToProp can find it is called when click button.

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>
    }
}

const mapStateToProps = (state) => {
    console.log(state)
    return state;
}

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


Open and click title A to title D, check console log.
It shows post information in state

沒有留言:

張貼留言

別名演算法 Alias Method

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