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