简体   繁体   English

带有箭头功能的渲染道具,Apollo和JSX道具

[英]Render props, Apollo, and JSX props with arrow functions

Many examples of how to Apollo involve something like 关于阿波罗的许多例子都涉及

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

  </Mutation>

These two rules conflict in ESLint rules and also in practice. 这两个规则在ESLint规则中以及在实践中都存在冲突。 We also know that JSX props should not use .bind() - how to avoid using bind? 我们也知道JSX道具不应该使用.bind()-如何避免使用bind? JSX props instantiating new arrow functions on each render aren't good practice. JSX道具在每个渲染器上实例化新的箭头功能不是一个好习惯。

  1. How/where do you write your update handlers? 您如何/在何处编写update处理程序?
  2. If the goal is to make as many "pure" functions as possible, what's the right way to attach a handler to the update prop? 如果目标是制作尽可能多的“纯”函数,那么将处理程序附加到update道具的正确方法是什么?

Create an update function in the component that's calling the Mutation component. 在调用Mutation组件的组件中创建一个更新函数。 Like so: 像这样:

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>
    )
  }
}

This way, you're not creating a new function every render, only when the Root component is mounted. 这样,您就不会在每个渲染器上都创建一个新函数,仅当安装了Root组件时。

EDIT: 编辑:

If the update is a pure function, you can put it outside of the class declaration altogether. 如果update是纯函数,则可以将其完全放在类声明之外。

The problem here is new handler every component re-render which can affect performance and lead to cascading re-renders of children. 这里的问题是新的处理程序会重新渲染每个组件,这可能会影响性能并导致儿童的级联重新渲染。

I think you should use one of the following approche: 我认为您应该使用以下方法之一:

1) Extract you function to module global const if don't need class context inside 1)如果内部不需要类上下文,则将您的函数提取为模块全局const

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

  </Mutation>
}

2) Class with arrow propertirs 2)带有箭属性的类

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

  </Mutation>
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM