iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 24
1
Modern Web

Zero to hero with React.js系列 第 24

【Day 24 React】Redux 做遊戲角色陣容應用程式——趴四

介面的呈現

在做好基本功能之後,先來把介面刻完,然後就可以把功能 map 到 UI 元件上了。
除了 import Reactcomponent 之外,我們需要從 react-redux 引入一個叫 connect 的 function。這個 function 允許我們在這個 component 裡存取 store 裡的 data

import React, { Component } from 'react';
import { connect } from 'react-redux';


class CharacterList extends Component{
  render(){
    return(
      <div>
        <h2>Characters</h2>
      </div>
    )
  }
}

export default connect()(CharacterList);

mapping state to props

CharacterList.js 裡撰寫 mapping 邏輯

function mapStateToProps(state){
  console.log('state', state);
  return {};
}

export 的地方要回傳兩個參數

export default connect(mapStateToProps, null)(CharacterList);

回到 App.js 裡,把 CharacterList 引入,在渲染的地方加上 <CharacterList />

import React, { Component } from 'react';
import CharacterList from './CharacterList';


class App extends Component{
  render(){
    return(
      <div>
          <h2>SuperSquad</h2>
          <CharacterList />
      </div>
    )
  }
}

export default App;

渲染結果~有看到我剛剛寫上的 Characters

mapping character

透過 this.props.characters.map 把 characterList 裡的 character.name render 出來

class CharacterList extends Component{
  render(){
    console.log('this.props', this.props);
    return(
      <div>
        <h4>Characters</h4>
        <ul>
          {
            this.props.characters.map(character => {
              return(
                <li key={character.id}>
                  <div>{character.name}</div>
                </li>
              )
            })
          }
        </ul>
      </div>
    )
  }
}


上一篇
【Day 23 React】Redux 做遊戲角色陣容應用程式——趴水
下一篇
【Day 25 React】Redux 做遊戲角色陣容應用程式——趴ㄈ ㄞˋ
系列文
Zero to hero with React.js30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言