import React from 'react';
import ReactDOM from 'react-dom';
import { useReducer } from 'react';
const NAME_DETAIL = 'name_detail';
const NAME_DETAIL_DEMO = 'name_detail_demo';
const myReducer = (state, action) => {
console.log(action, 'action')
switch(action.Demotype) {
case NAME_DETAIL : {
return {
name: 'ww'
}
}
case NAME_DETAIL_DEMO : {
return {
name: 'dd'
}
}
default: {
return {
name: 'pp'
}
}
}
};
const Demo = () => {
const initValue = {name: 'gaga'}; // 为state的初始值
// myReducer为dispatch的回调函数,只能通过dispatch才能触发myReducer
const [ state, dispatch ] = useReducer(myReducer, initValue);
const clickButton = () => {
dispatch({
type: NAME_DETAIL_DEMO
});
}
return <>
i am demo {state.name}
<button onClick={clickButton}>demo button</button>
</>;
}
const Test = () => {
const [state, dispatch] = useReducer( myReducer, { name: 'wp' });
const clickButton = () => {
dispatch({
type: NAME_DETAIL
});
};
return <>
{state.name}
<button onClick={clickButton}>click</button>
<br/>
<Demo></Demo>
</>;
}
ReactDOM.render(<Test />, document.getElementById('root'));
网友评论