react 16.7.0-alpha.2版本中推出了新版本的react-hook,官方文档对于react hook的解释已经很详细了,
react hook中主要的作用是写出不需要class的组件,也就是从前的stateless component变成function component
复制代码
使用hook
以前的stateless component,使用起来虽然简洁,但是由于收到stateless的影响,其自身是没有state这个概念的,只是一个纯函数,自身可变部分只能从父组件处得来,或者没有可变部分;
hook使得我们不需要class,也可以更方便地写出带有state的function component,component可以维持自身的state;
hook主要使用的api官方文档中有介绍,hook使用的规则中,有两条:
1.不要将hook放入条件/循环/嵌套函数中,这点的原因,官网描述得很清楚,会造成渲染错误;
2.只在react functions中调用Hooks,保证代码的可读性;
下面是使用react hook实现todo list的例子:
import React, { useState, useEffect } from 'react';
import './App.css';
function TodoForm({addTodo}){
const [value, setValue] = useState("");
const handleSubmit = e => {
e.preventDefault();
if(!value) return;
addTodo(value);
setValue("");
}
return (
<form onSubmit={handleSubmit}>
<input
type="text"
value={value}
onChange={e => setValue(e.target.value)}
/>
</form>
)
}
function App (props){
const [todos, setTodos] = useState([
{
text: "learn react hook",
isCompleted: false
},
{
text: "optimize dynamic loding",
isCompleted: false
},
{
text: "learn redux-saga",
isCompleted: false
},
]);
const addTodo = (text) => {
const newTodos = [...todos, {text}];
setTodos(newTodos);
};
const completeTodo = index => {
const newTodos = [...todos];
newTodos[index].isCompleted = true;
setTodos(newTodos);
};
const removeTodo = index => {
const newTodos = [...todos];
newTodos.splice(index, 1);
setTodos(newTodos);
}
const Todo = ({todo, index}) => <li
style={{textDecoration: todo.isCompleted ? "line-through" : ""}}
>
{todo.text}
<button onClick={() => completeTodo(index)}>Complete</button>
<button onClick={() => removeTodo(index)}>x</button>
</li>
return <div>
<ul>
{todos.map((item, index) =>
<Todo key={index}
index={index}
todo={item}
/>
)}
</ul>
<TodoForm addTodo={addTodo}/>
</div>
}
export default App;
复制代码