redux - show selected information in another component

Commit

Flow
Add PttPostContent.js
import React, {Component} from "react";
import {connect} from 'react-redux'

const PttPostContent = ({pttPost}) => {
    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}
}

export default connect(mapStateToProps)(PttPostContent)

Add PttPostContent component to App.js
import React from 'react';
import PttPosts from "./components/PttPosts";
import PttPostContent from "./components/PttPostContent"

function App() {
  return (
      <div>
          <div>
              <PttPosts />
          </div>
          <div>
              <PttPostContent />
          </div>
      </div>
  );
}

export default App;

When button in PttPosts list was clicked, selectPttPost will be called
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)

Based on the function, selectPttPost will be called
src/actions/index.js
export const selectPttPost = pttPost => {
    return {
        type: "PTT_POST_SELECTED", //required attribute
        payload: pttPost
    };
};

mapStateToProps in PttPostContent will be called as well



沒有留言:

張貼留言

別名演算法 Alias Method

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