LoginSignup
1
1

More than 3 years have passed since last update.

React hooks useReducer

Last updated at Posted at 2019-09-23
  • Store.jsでApp.jsをラップする
  • iniialStateを設定をしないとnilでえら0になる

キーワード

  • createContext ← Proveider的な役割をしている
  • useReducer
  • store
  • )}


<TodoItem key={item.id} {...item}/>)}

どっちも取れる
# id
function TodoItem({id}){
  return (<div>{id}</div> )
}
# text
function TodoItem({text}){
  return (<div>{text}</div> )
}
src/App.js

import React, {Component} from 'react';
import logo from './logo.svg';
import './App.css';
import Store from './store'
import Fruits from './Fruits'

class App extends Component{
  constructor(props){
    super(props)
    this.state ={
      name: "react"
    }
  }

  render(){
    return (
      <Store>
       <div className="App">
        <Fruits/>
      </div>
      </Store>
    );
  }
}

export default App;


src/Fruit.js

import React, {useContext} from 'react';
import {StoreContext} from './store'

const Fruits = () => {
  const [state, dispatch] = useContext(StoreContext);
  return(
      <div>
          <h1>Fruits</h1>
          <button onClick={() => dispatch({type:"addFruit", payload:"bnana"})}>add Banana</button>
          <button onClick={() => dispatch({type:"addFruit", payload:"apple"})}>add Apple</button>
          <ul>
          {state.fruits.map(fruit => <li>{fruit}</li>)}
          </ul>

      </div>
  )
}

export default Fruits


src/store.js

import React, {createContext, useReducer} from 'react';


// これがcreateStore的なやつか? createContext is Provider
export const StoreContext = createContext({})


const initialState = {fruits: []}

function reducer(state, action){
  switch (action.type){
    case 'addFruit':
      return {fruits: [...state.fruits, action.payload]}
    case 'addVeggitable':
      return {vegetables: [...state.vegetables, action.payload]}
    default: throw new Error("action type must....") 
  }    
}

const Store = ({children}) =>{
   const [state, dispatch] = useReducer(reducer, initialState)
   return(
       <StoreContext.Provider value={[state, dispatch]}>{children}</StoreContext.Provider>
   )   
}

export default Store;

youtube

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1