1.React 列表 & Keys
Keys
比方说,如果你提取出一个 ListItem 组件,你应该把 key 保存在数组中的这个 <ListItem />
元素上,而不是放在 ListItem 组件中的 <li>
元素上。
当你在 map() 方法的内部调用元素时,你最好随时记得为每一个元素加上一个独一无二的 key。
function ListItem(props) {
// 对啦!这里不需要指定key:
return <li>{props.value}</li>;
}
function NumberList(props) {
const numbers = props.numbers;
const listItems = numbers.map((number) =>
// 又对啦!key应该在数组的上下文中被指定
<ListItem key={number.toString()}
value={number} />
);
return (
<ul>
{listItems}
</ul>
);
}
const numbers = [1, 2, 3, 4, 5];
ReactDOM.render(
<NumberList numbers={numbers} />,
document.getElementById('example')
);
在 jsx 中嵌入 map()
这么做有时可以使你的代码更清晰,但有时这种风格也会被滥用。就像在 JavaScript 中一样,何时需要为了可读性提取出一个变量,这完全取决于你。但是,如果一个 map() 嵌套了太多层级,那你就可以提取出组件。
function ListItem(props) {
return <li>{props.value}</li>;
}
function NumberList(props) {
const numbers = props.numbers;
return (
<ul>
{numbers.map((number) =>
<ListItem key={number.toString()}
value={number} />
)}
</ul>
);
}
const numbers = [1, 2, 3, 4, 5];
ReactDOM.render(
<NumberList numbers={numbers} />,
document.getElementById('example')
);
{} 中不能出现var,const,let等这种关键字
function NumberList(props) {
var numbers; //声明在外面是因为 {} 中不能出现var,const,let等这种关键字
return (
<ul>
{
numbers = props.numbers, //注意这里要加逗号
numbers.map((number) =>
<ListItem key={number}
value={number} />
)}
</ul>
);
}
2.React组件 API
设置状态:setState setState()总是会触发一次组件重绘
替换状态:replaceState
replaceState()方法与setState()类似,但是方法只会保留nextState中状态,原state不在nextState中的状态都会被删除。
设置属性:setProps
替换属性:replaceProps
强制更新:forceUpdate
forceUpdate()方法适用于this.props和this.state之外的组件重绘(如:修改了this.state后),通过该方法通知React需要调用render()
一般来说,应该尽量避免使用forceUpdate()
获取DOM节点:findDOMNode
判断组件挂载状态:isMounted
关于setState()
(1)构造函数是唯一能够初始化 this.state 的地方。
// Wrong
this.state.comment = 'Hello';
//应当使用 setState():
// Correct
this.setState({comment: 'Hello'});
(2状态更新可能是异步的
React 可以将多个 setState() 调用合并成一个调用来提高性能。
因为 this.props 和 this.state 可能是异步更新的,你不应该依靠它们的值来计算下一个状态。
例如,此代码可能无法更新计数器:
// Wrong
this.setState({
counter: this.state.counter + this.props.increment,
});
要修复它,请使用第二种形式的 setState() 来接受一个函数而不是一个对象。 该函数将接收先前的状态作为第一个参数,将此次更新被应用时的props做为第二个参数:
// Correct
this.setState((prevState, props) => ({
counter: prevState.counter + props.increment
}));
上方代码使用了箭头函数,但它也适用于常规函数:
// Correct
this.setState(function(prevState, props) {
return {
counter: prevState.counter + props.increment
};
});
(3)状态更新合并
当你调用 setState() 时,React 将你提供的对象合并到当前状态。
constructor(props) {
super(props);
this.state = {
posts: [],
comments: []
};
}
你可以调用 setState() 独立地更新它们:
componentDidMount() {
fetchPosts().then(response => {
this.setState({
posts: response.posts
});
});
fetchComments().then(response => {
this.setState({
comments: response.comments
});
});
}
这里的合并是浅合并,也就是说 this.setState({comments}) 完整保留了 this.state.posts,但完全替换了 this.state.comments。
isMounted()
isMounted 的方法在 ES6 中已经废除。主要的原因是它经过实际使用与测试可能不足以检测组件是否挂载,尤其是对于有一些异步的程序情况,以及逻辑上造成混乱。现在用以下方法代替:
componentDidMount() {
this.mounted = true;
}
componentWillUnmount() {
this.mounted = false;
}
React中动态生成key的方式
this.setState({
[name]: value
});
3.React 组件生命周期
componentWillMount 在渲染前调用,在客户端也在服务端。
componentDidMount : 在第一次渲染后调用,只在客户端。之后组件已经生成了对应的DOM结构,可以通过this.getDOMNode()来进行访问。 如果你想和其他JavaScript框架一起使用,可以在这个方法中调用setTimeout, setInterval或者发送AJAX请求等操作(防止异步操作阻塞UI)。
componentWillReceiveProps 在组件接收到一个新的 prop (更新后)时被调用。这个方法在初始化render时不会被调用。
shouldComponentUpdate 返回一个布尔值。在组件接收到新的props或者state时被调用。在初始化时或者使用forceUpdate时不被调用。
可以在你确认不需要更新组件时使用。
当shouldComponentUpdate返回true时,修改props或者state之后,componentWillUpdate与componentDidUpdate将会被调用;当shouldComponentUpdate返回false时,修改props或者state之后,componentWillUpdate与componentDidUpdate不会被调用。
componentWillUpdate在组件接收到新的props或者state但还没有render时被调用。在初始化时不会被调用。
componentDidUpdate 在组件完成更新后立即调用。在初始化时不会被调用。
componentWillUnmount在组件从 DOM 中移除之前立刻被调用。
4.React Refs
点击按钮输入框获取焦点
class MyComponent extends React.Component {
handleClick() {
// 使用原生的 DOM API 获取焦点
this.refs.myInput.focus();
}
render() {
// 当组件插入到 DOM 后,ref 属性添加一个组件的引用于到 this.refs
return (
<div>
<input type="text" ref="myInput" />
<input
type="button"
value="点我输入框获取焦点"
onClick={this.handleClick.bind(this)}
/>
</div>
);
}
}
ReactDOM.render(
<MyComponent />,
document.getElementById('example')
);