0
点赞
收藏
分享

微信扫一扫

redux学习笔记 无状态组件与有状态组件

小云晓云 2022-01-31 阅读 68

1.什么是无状态组件?

只有一个render函数的组件,就可以写成无状态组件,
一个函数没有props,没有生命周期, 就是一个简单的视图函数,没有业务逻辑更纯粹的展示UI。
例子:例子如下:

import React, {Component} from "react";
import {connect} from "react-redux";
import {getChangeInputAction, getBtnClickAction, getHandleDeleteAction} from "./store/actionCreators";
//只有一个render方法可以写成无状态组件,能用最好用
const TodoList = (props) =>{
    const {inputValue,list, changeInputValue, handleBtnClick, handleDelete} = props
    //优化精简
    return(
        <div>
            <div>
                <input value={inputValue} onChange={changeInputValue}/>
                <button onClick={handleBtnClick}>tijiao</button>
            </div>

            <ul>
                {list.map((item,index) => {
                    return <li onClick={()=>{handleDelete(index)}} key = {index} >{item}</li>
                })}
            </ul>
        </div>
    )
}

const mapStateToProps = (state) => {
    return {
        inputValue: state.inputValue,
        list: state.list
    }
}

const mapDispatchToProps = (dispatch) => {
    return{
        changeInputValue(e){
            console.log(e.target.value)
            const action = getChangeInputAction(e.target.value)
            dispatch(action)
        //action被dispatch只是dispatch到store,store把action转发给reducer
        },

        handleBtnClick(){
            const action = getBtnClickAction()
            dispatch(action)
        },

        handleDelete(index){
            const action = getHandleDeleteAction(index)
            dispatch(action)
        }

    }

}
export default connect(mapStateToProps, mapDispatchToProps)(TodoList);

2.有状态组件

有状态组件主要用来定义交互逻辑和业务数据(如果用了Redux,可以把业务数据抽离出去统一管理),使用{this.state.xxx}的表达式把业务数据挂载到容器组件的实例上(有状态组件也可以叫做容器组件,无状态组件也可以叫做展示组件),然后传递props到展示组件,展示组件接收到props,把props塞到模板里面。

import React, {Component, PureComponent} from "react";
import {RecommendBoard, RecommendItem} from '../style'
import {connect} from "react-redux";
import {SearchInfoItem} from "../../../common/header/style";

class Recommend extends PureComponent{
    render() {
        const {list, page} = this.props

        return(

            <RecommendBoard>
                {


                    list.map((item) => {
                        return(
                    <RecommendItem key = {item.get('id') }  href ={item.get('href')}>
                    <img alt=''   className='pic' src={item.get('imgUrl')} ></img>
                    </RecommendItem>
                    )
                })



                }

            </RecommendBoard>
        )
    }
}

const mapState = (state) => ({
    list : state.getIn(['home','recommendList'])
})

export default connect(mapState)(Recommend);

举报

相关推荐

0 条评论