javascript 列表无状态与重构

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 列表无状态与重构相关的知识,希望对你有一定的参考价值。

import React from "react";
import { pure, withReducer, compose, withHandlers, mapProps } from "recompose";
import R from "ramda";
import { createReducer } from "./utils";

const ListItem = pure(({ text }) => <li>{text}</li>);
const renderItems = R.map(t => <ListItem key={t} text={t} />);

const ListComponent = ({ todos, name, updateName, addTodo }) =>
  <div>
    <input onChange={updateName} value={name} />
    <button onClick={() => addTodo(name)}>add todo</button>
    <ul>
      {renderItems(todos)}
    </ul>
  </div>;

const initialState = { todos: [], name: "" };
const listReducer = createReducer({
  UPDATE_NAME: (state, payload) => ({ name: payload }),
  ADD_TODO: (state, payload) => ({ todos: [...state.todos, payload] })
});

const List = compose(
  withReducer("state", "dispatch", listReducer, initialState),
  withHandlers({
    updateName: ({ dispatch }) => e =>
      dispatch({ type: "UPDATE_NAME", payload: e.target.value }),
    addTodo: ({ dispatch, name }) => name =>
      dispatch({ type: "ADD_TODO", payload: name })
  }),
  mapProps(({ state, ...props }) => ({ ...state, ...props }))
)(ListComponent);

export default List;

以上是关于javascript 列表无状态与重构的主要内容,如果未能解决你的问题,请参考以下文章

javascript React传递组件状态(状态与无状态)组件pt1

重构你的 javascript 代码

[Effective JavaScript 笔记]第56条:避免不必要的状态

关于javascript闭包与重构

javascript REACT:基本无状态功能组件

javascript 无状态Redux减速机