父传子,方法写到父亲里面,子函数回调。这样写的原因是。兄弟组件可能会用到子组件传递给父组件的值。所以这样写。
把所有的像ajax请求,localstorage,sessionstorge,把一些元素dom的操作都理解为副作用。
引入状态
useContext():共享状态钩子,函数里面套函数,然后是函数式组件。
import React, { useContext } from "react";
const Ceshi = () => {
const AppContext = React.createContext({});
const A = () => {
const { name } = useContext(AppContext);
return (
<p>
我是A组件的名字{name}
<span>我是A的子组件{name}</span>
</p>
);
};
const B = () => {
const { name } = useContext(AppContext);
return <p>我是B组件的名字{name}</p>;
};
return (
<AppContext.Provider value={{ name: "hook测试" }}>
<A />
<B />
</AppContext.Provider>
);
};
export default Ceshi;
import React, { useReducer } from "react";
const AddCount = () => {
const reducer = (state, action) => {
if (action.type === "add") {
return {
...state,
count: state.count + 1,
};
} else {
return state;
}
};
const addcount = () => {
dispatch({
type: "add",
});
};
const [state, dispatch] = useReducer(reducer, { count: 0 });
return (
<>
<p>{state.count}</p>
<button onClick={addcount}>count++</button>
</>
);
};
export default AddCount;
https://www.jianshu.com/p/d600f749bb19