【问题标题】:Render props, Apollo, and JSX props with arrow functions使用箭头函数渲染道具、Apollo 和 JSX 道具
【发布时间】:2018-11-24 12:29:11
【问题描述】:

Apollo 的许多示例都涉及到类似

<Mutation
     mutation={YOUR_MUTATION}
     update={(cache, { data }) => {
         // do stuff to update Apollo store
     }}
 >
   { mutate => ( <UI mutate={mutate} /> ) }

  </Mutation>

这两个规则在 ESLint 规则和实践中都存在冲突。我们也知道 JSX props should not use .bind() - how to avoid using bind? JSX 道具在每次渲染时实例化新的箭头函数并不是好的做法。

  1. 您如何/在哪里编写您的 update 处理程序?
  2. 如果目标是制作尽可能多的“纯”函数,那么将处理程序附加到 update 属性的正确方法是什么?

【问题讨论】:

  • 您提到的答案已经提出了一个解决方案 - 使用类方法(例如,在构造函数中绑定或更好的箭头函数作为类属性)

标签: javascript reactjs apollo react-apollo


【解决方案1】:

这里的问题是每个组件重新渲染的新处理程序会影响性能并导致子级的级联重新渲染。

我认为您应该使用以下方法之一:

1) 如果内部不需要类上下文,则将函数提取到模块 global const

const handler = () => {//asdfasdf}
const component = () => {
  return <Mutation
     mutation={YOUR_MUTATION}
     update={handler}
 >
   { handler ) }

  </Mutation>
}

2) 带有箭头属性的类

class Component extends React.Component {
  update = (u) => this.props.update;
  render () {
    return <Mutation
     mutation={YOUR_MUTATION}
     update={this.update}
 >
   { etc... }

  </Mutation>
  }
}

【讨论】:

    【解决方案2】:

    在调用Mutation 组件的组件中创建一个更新函数。像这样:

    class Root extends React.Component {
      update = (cache, { data }) => {
        // do stuff to update Apollo store
      };
    
      render() {
        return (
          <Mutation
            mutation={YOUR_MUTATION}
           update={this.update}
          >
            {mutate => (<UI mutate={mutate} />)}
          </Mutation>
        )
      }
    }
    

    这样,您不会在每次渲染时都创建一个新函数,只有在安装 Root 组件时。

    编辑:

    如果update 是一个纯函数,你可以把它放在类声明之外。

    【讨论】:

      猜你喜欢
      • 2019-01-10
      • 2021-05-14
      • 2017-05-25
      • 1970-01-01
      • 1970-01-01
      • 2020-03-10
      • 1970-01-01
      • 2021-08-19
      相关资源
      最近更新 更多