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);
渲染过程发生了什么? 1.调用root.render()函数,传入作为参数 2.React调用Welcome组件,并将{name: 'Sara'}作为props传入 3.Welcome组件将

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>
    );
  }
}
componentDidMount()方法会在组件已经被渲染到DOM中后运行, 一旦Clock组件从DOM中被移除,React就会调用componentWillUnmount()生命周期方法,这样计时器就停止了。

二、正确地使用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
}));
3.State的更新会被合并 当你调用setState()的时候,React会把你提供的对象合并到当前的state
点击查看代码
 componentDidMount() {
    fetchPosts().then(response => {
      this.setState({
        posts: response.posts
      });
    });

    fetchComments().then(response => {
      this.setState({
        comments: response.comments
      });
    });
  }
浅合并 setState({posts})修改了this.state.posts,但是完整保留了this.state.comments

三、数据是向下流动的
不论父组件和子组件都不知道某个组件是有状态还是无状态的,并且它们也不关心它是函数组件还是类组件
这就是为啥state为局部的或是封装的原因。除了拥有并设置它的组件,其他组件都无法访问
组件可以选择把它的state作为props向下传递到它的子组件中:

点击查看代码
<FormattedDate date={this.state.date} />
FormattedDate组件本身无法知道它来自与clock的state,或是props,还是手动输入 这通常叫做“自上而下”或是“单向”的数据流。 每一个组件的state就像是在任意一点上给瀑布增加额外的水源,但是它只能向下流动

条件渲染
一、与运算符&&
通过花括号包裹代码,你可以在jsx中嵌入表达式。
在JavaScript中,true&&expression总是会返回expression,而false&&expresion总是会返回false
因此,如果条件是true,&&右侧的元素就会被渲染,如果是false,React会忽略并跳过它。
*falsey表达式
如果第一个对象是虚假的,则返回该对象
false && "dog" // false
0 && "dog" // 0

posted @   baller  阅读(20)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示