八十、React中的容器组件和无状态组件
生活随笔
收集整理的這篇文章主要介紹了
八十、React中的容器组件和无状态组件
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
| 2020/11/20、 周五、今天又是奮斗的一天。 |
@Author:Runsen
React,也有了自己去構建一些應用的信心,那會是一種非常棒的感覺。
容器組件和無狀態組件
React類組件是在JavaScript ES6時引入的,因為直到ES6才支持JS類。有時候它們也被稱為React ES6類組件。
在上次的TodoList示例中,render函數是、渲染一個組件,而這個組件叫做UI組件。
新建TodoListUI.js,來做無狀態組件
有狀態組件其實就是一個類,也叫容器組件,而無狀態組件是一個函數
從上面定義我們看到的明顯區別是:有狀態組件其實就是一個類,而無狀態組件是一個函數。
從數據管理和存儲來看:有狀態組件可以使用State ,而無狀態組件不能使用state,而是使用props來接收數據。
TodoListUI.js
import React from 'react' import { Input,Button, List } from 'antd';// const無狀態組件 父項子傳參數 需要props const TodoListUI = (props)=> {return (<div><div><Input value={props.inputValue}placeholder="Todo info" style={{width:'300px',marginRight:'10px' }}onChange={props.handleInputChange}></Input><Button type="primary"onClick={props.handleBtnClick}>提交</Button></div><Listborderedstyle={{width:'300px',marginTop:'10px' }}dataSource={props.list}renderItem={(item, index) => (<List.Item onClick={()=>{props.handleItemDelete(index)}}>{item}</List.Item>)}/></div>)}export default TodoListUI;使用JavaScript類編寫的React Component有個類似于類構造器的方法,主要用于讓React設置初始狀態,或者綁定方法。還有必須的render方法用于返回JSX的輸出。
TodoList.js
import React, {Component } from 'react' import 'antd/dist/antd.css' import store from './store'; import TodoListUi from './TodoListUI'; import { getInitList, getInputChangeAction, getAddItemAction, getDeleteItemAction } from './store/actionCreators'class TodoList extends Component {constructor(props) {super(props)this.state = store.getState()this.handleInputChange = this.handleInputChange.bind(this)this.handleStoreChange = this.handleStoreChange.bind(this)this.handleBtnClick = this.handleBtnClick.bind(this)this.handleItemDelete = this.handleItemDelete.bind(this)store.subscribe(this.handleStoreChange)console.log( this.state)}render() {return <TodoListUiinputValue={this.state.inputValue}handleInputChange={this.handleInputChange}handleBtnClick={this.handleBtnClick}handleItemDelete={this.handleItemDelete}list={this.state.list}/>}componentDidMount() {const action = getInitList();store.dispatch(action);}handleInputChange(e) {const action = getInputChangeAction(e.target.value);store.dispatch(action);}handleStoreChange() {this.setState(store.getState());}handleBtnClick() {const action = getAddItemAction();store.dispatch(action);}handleItemDelete(index) {const action = getDeleteItemAction(index);store.dispatch(action);} }export default TodoList;在實際開發中,建議更多的使用無狀態組件,因為有狀態組件帶有生命周期函數,會在不同時刻觸發更新。所以更多的使用無狀態組件可以提高整體的渲染性能。
總結
以上是生活随笔為你收集整理的八十、React中的容器组件和无状态组件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 零钱通为什么没有收益
- 下一篇: 沪企债30是啥意思 其实债券也是有指数的