React 无状态组件

67 阅读1分钟

无状态组件主要用来定义模板,接收来自父组件props传递过来的数据,使用 {props.xxx} 的表达式把 props 塞到模板里面;当一个组件只有 render 函数的时候我们完全可以通过无状态组件替换掉普通组件。 优点:无状态组件性能比较高,因为它就是一个函数;普通组件它是js里面的类,这个类生成的对象里面还会生成生命周期函数; 一个组件只有render,请使用无状态组件

todoList示例,直接复制的例子包含了redux代码,可看Redux安装、使用文章

import React, {useState} from 'react';
import Store from '../../store';  //导入store
import {getInputChange, getAddItem, getDeleteTodoItem} from '../../store/actionCreators'; //导入 actionCreators 方法
import {Button, Input, Message} from '@alifd/next';
import List from './components/list';
import styles from './index.module.scss';

export default function TodoList() {
  const [storeState, setStoreState] = useState(Store.getState()); //获取 Redux 数据 .getState()
  Store.subscribe(storeChange); //订阅 Redux 的改变,只要 Redux 发生改变 storeChange方法就会自动执行一次

  //重新获取 Redux 数据
  function storeChange() {
    setStoreState(Store.getState());
  }

  //删除方法,参数为下标
  function deleteListItem(index) {
    const action = getDeleteTodoItem(index)
    Store.dispatch(action); //调用 dispatch 并传递参数给 Redux
  }

  return (
    <div className={styles.todoList}>
      <div className={styles.todoSo}>
        <Input
          placeholder="请输入"
          value={storeState.inputValue}
          onChange={(e) => {
            const action = getInputChange(e)
            Store.dispatch(action);
          }}
          className={styles.todoInput}/>
        <Button
          type="primary"
          className={styles.todoButton}
          onClick={() => {
            if (storeState.inputValue){
              const action = getAddItem();
              Store.dispatch(action);
            }else{
              Message.error('输入不能为空');
            }
          }}>添加</Button>
      </div>
      <ul className={styles.todoUl}>
        {storeState.list.map((item, index) => (
          <List key={index} item={item} index={index} deleteItem={deleteListItem}/>
        ))}
      </ul>
    </div>
  );
};

子组件 无状态组件

import React from 'react';

const List = (props) =>{
  return (
    <li onClick={props.deleteItem.bind(this, props.index)}>{props.index} - {props.item}</li>
  );
}

export default List;