React学习笔记
6.15
组件与Props
一.渲染组件
当React元素为自定义组件时,它会将JSX所接收的属性以及子组件转换为单个对象传递给组件,这个对象被称之为“props”
点击查看代码
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
const root = ReactDOM.createRoot(document.getElementById('root'));
const element = <Welcome name="Sara" />;
root.render(element);
Hello,Sara
元素作为返回值 4.React Dom 将DOM高效地更新为Hello,Sara
*所有React组件都必须像纯函数一样保护它们的props不被更改
State & 生命周期
一.将生命周期方法添加到Class中
在具有许多组件的应用程序中,当组件被销毁时释放所占用的资源是非常重要的。
点击查看代码
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),1000
)
}
componentWillUnmount() {
clearInterval(this.timerID)
}
tick(){
this.setState({
date: new Date()
})
}
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
二、正确地使用State
1.不要直接修改State
//wrong
this.state.comment = 'Hello'
//correct
this.setState({comment:'Hello'})
2.State的更新可能是异步的
出于性能考虑,React可能会把多个setState()调用合并成一个调用
因为this.props和this.state可能会异步更新,所以不要依赖他们的值来更新下一个状态。
点击查看代码
// Wrong
this.setState({
counter: this.state.counter + this.props.increment,
});
// Correct
this.setState((state, props) => ({
counter: state.counter + props.increment
}));
点击查看代码
componentDidMount() {
fetchPosts().then(response => {
this.setState({
posts: response.posts
});
});
fetchComments().then(response => {
this.setState({
comments: response.comments
});
});
}
三、数据是向下流动的
不论父组件和子组件都不知道某个组件是有状态还是无状态的,并且它们也不关心它是函数组件还是类组件
这就是为啥state为局部的或是封装的原因。除了拥有并设置它的组件,其他组件都无法访问
组件可以选择把它的state作为props向下传递到它的子组件中:
点击查看代码
<FormattedDate date={this.state.date} />
条件渲染
一、与运算符&&
通过花括号包裹代码,你可以在jsx中嵌入表达式。
在JavaScript中,true&&expression总是会返回expression,而false&&expresion总是会返回false
因此,如果条件是true,&&右侧的元素就会被渲染,如果是false,React会忽略并跳过它。
*falsey表达式
如果第一个对象是虚假的,则返回该对象
false && "dog" // false
0 && "dog" // 0
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!