函数式组件:
1.属性的差异(属性约束及默认值)
2.利用useState进行状态的操作与处理(类似于class组件中的state),而useState我们称为hooks(钩子)
3.useState的使用
1)useState是一个函数,函数的参数是默认值,并且它将返回一个数组,该数组有2个内容,第一个是state状态值,第二个是fn方法,该方法可以设置state的状态值
2)需要利用const进行解构赋值,因为useState返回[state,fn],所以const解构以后也会有state以及setState的fn函数这两个内容
3)不管是useState还是this.setState都有prevState的操作,prevState是前一个状态值,特别是在循环等操作时不能直接处理state,需要处理的是前一个状态值的内容
/*
函数式组件的特点:
1.函数式组件是没有state的
2.函数式组件是没有lifeCycle生命周期钩子函数的
*/
const Child = (props) => {
const [emailText, setEmailText] = useState("");
// 在函数式组件中定义调用函数
const changeEmailText = (text) => {
setEmailText(text);
};
// componentWillMount/ componentWillUnmount
useEffect(() => {
// 第一个部分的内容就是 componentWillMount
Keyboard.addListener("keyboardDidShow", () => {
console.log("keyboardDidShow");
});
Keyboard.addListener("keyboardDidHide", () => {
console.log("keyboardDidHide");
});
// 利用return 返回一个函数,相当于componentWillUnmount钩子函数
return () => {
console.log("删除组件");
};
}, []);
return (
<View style={styles.container}>
<Text>当前是Child组件</Text>
<TextInput
style={{
backgroundColor: "gray",
width: 100,
height: 50,
borderWidth: 2,
borderColor: "black",
}}
value={emailText}
placeholder="请输入邮箱内容"
placeholderTextColor="#ffcc00"
keyboardType="email-address"
autoCapitalize="none"
autoFocus={true}
onChangeText={changeEmailText}
></TextInput>
</View>
);
};
const App = () => {
const [count, setCount] = useState(0);
const increase = () => {
setCount(count + 1);
};
const increaseFive = () => {
// prevState
for (let i = 0; i <= 5; i++) {
setCount((prevState) => prevState + 1);
/*
this.setState((prevState)=>{
return prevState.count +1
},()=>{
console.log('state updated')
})
*/
}
};
const resetCount = () => {
setCount(0);
};
return (
<View style={styles.container}>
<Text>Count:{count}</Text>
<Button title="reset" onPress={resetCount}></Button>
<Button title="count++" onPress={increase}></Button>
<Button title="count+5" onPress={increaseFive}></Button>
</View>
);
};
4.useEffect的使用
1)useEffect有两个参数,第一个参数是回调函数,第二个参数是依赖数组
2)回调函数中的操作相当于componentWillMount或者getDerivedStateFromProps
3)回调函数中可以进行return返回,而返回的是一个函数,该函数相当于componentWillUnmount钩子函数的功能
// 1.如果第二个参数依赖项为空,在react当中将会不断的的执行
// 2.如果在react当中,第二个参数假设为空数组,第一个回调函数将执行一次,类似于componentWillMount的初始加载
// 3.如果说有依赖项,依赖项可以1个到多个,都会进行回调函数的执行
useEffect与生命周期的比较(componentWillMount+componentWillUnmount+shouldComponentUpdate+componentDidUpdate)
useState 主要解决的是类似state的初始设置以及this.setState的修改操作
useEffect 相当于类组件中诸多生命周期钩子函数的组合,比如componentWillMount、componentWillUnmount、shouldComponentUpdate(性能优化),componentWillUpdate
useRef 相当于ref,而ref的设置主要包括字符串(被抛弃了),回调函数,useRef以及createRef
createRef ref的问题主要解决的是对象的查找以及对象方法的调用
createContext 创建上下文 Provider和Consumer,Consumer应用的是函数,写法比较麻烦
useContext 解决多个对象获取,或者更方便的获取上下文
useReducer 相当于react-redux中的reducer,包含state以及dispatch
useCallback 将会把方法转存到缓存当中,调用的时候仍旧是方法的调用
useMemo 将会把方法转存到缓存当中,调用的时候将会变成计算方式