React Redux 整合實務 - Switch


Posted by YongChenSu on 2020-12-14

React Redux 整合實務 - Switch

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>My redux-switch </title>
  <style type="text/css">
    .switch{background-color:#cccccc;width:60px;height:30px;border-radius:15px;}
    .switch>.btn{background-color:#444444;width:30px;height:30px;border-radius:15px;}
    .switch-on{background-color:#aaffaa;}
    .switch-on>.btn{background-color:#006600;margin-left:30px;}
  </style>
  <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
  <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
  <script src="https://unpkg.com/redux@4.0.5/dist/redux.min.js"></script>
  <script type='text/babel'>
    class Button extends React.Component {
      render() {
        return <div className='btn'></div>
      }
    }

    class Switch extends React.Component {
      constructor(props) {
        super(props)
        this.state = store.getState()
      }

      // 連接 Redux 的狀態更新
      componentDidMount() {
        this.unsubscribe = store.subscribe(this.refresh.bind(this))
      }

      componentWillUnmount() {
        this.unsubscribe()
      }

      refresh() {
        this.setState(store.getState())
      }

      update() {
        store.dispatch({
          type: "ChangeSwitch",
        })
      }

      render() {
        return (
          <div 
            className={'switch' + (this.state.on 
              ? ' switch-on' 
              : '')}
            onClick={this.update.bind(this)}>
            <Button />
          </div>
        )
      }
    }

    let store
    let reducer = (state, action) => {
      switch(action.type) {
        case "ChangeSwitch":
          return { on: !state.on}
        default:
          return state
      }
    }

    window.addEventListener('load', () => {
      store = Redux.createStore(reducer, {on: false})
      ReactDOM.render(
        <Switch />,
        document.body
      )
    })
  </script>
</head>
<body>
</body>
</html>


參考資源


#程式導師實驗計畫第四期 #前端 #react book #Redux #switch







Related Posts

常用的 React Hooks 簡介

常用的 React Hooks 簡介

只是看看 JSON 檔案格式

只是看看 JSON 檔案格式

flexbox 子元素 的語法

flexbox 子元素 的語法


Comments