Javascript 使用箭头函数渲染道具、阿波罗和JSX道具
许多关于阿波罗的例子包括Javascript 使用箭头函数渲染道具、阿波罗和JSX道具,javascript,reactjs,apollo,react-apollo,Javascript,Reactjs,Apollo,React Apollo,许多关于阿波罗的例子包括 <Mutation mutation={YOUR_MUTATION} update={(cache, { data }) => { // do stuff to update Apollo store }} > { mutate => ( <UI mutate={mutate} /> ) } </Mutation> { //做一些事情来更新阿波罗商店 }} >
<Mutation
mutation={YOUR_MUTATION}
update={(cache, { data }) => {
// do stuff to update Apollo store
}}
>
{ mutate => ( <UI mutate={mutate} /> ) }
</Mutation>
{
//做一些事情来更新阿波罗商店
}}
>
{mutate=>()}
这两个规则在ESLint规则和实践中都存在冲突。我们还知道,JSX道具在每个渲染上实例化新的arrow函数不是很好的实践
更新处理程序
update
prop的正确方法是什么在调用
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>
)
}
}
类根扩展React.Component{
更新=(缓存,{data})=>{
//做一些事情来更新阿波罗商店
};
render(){
返回(
{mutate=>()}
)
}
}
这样,您就不会在每次渲染时都创建新函数,只有在装入Root
组件时才会创建新函数
编辑:
如果更新是一个纯函数,你可以把它放在类声明之外。这里的问题是每个组件都会重新呈现新的处理程序,这会影响性能并导致子组件的级联重新呈现 我认为你应该使用以下方法之一: 1) 如果内部不需要类上下文,则将函数提取到模块全局常量
const handler = () => {//asdfasdf}
const component = () => {
return <Mutation
mutation={YOUR_MUTATION}
update={handler}
>
{ handler ) }
</Mutation>
}
consthandler=()=>{//asdfasdf}
常量组件=()=>{
返回
{handler}
}
2) 使用箭头属性初始化
class Component extends React.Component {
update = (u) => this.props.update;
render () {
return <Mutation
mutation={YOUR_MUTATION}
update={this.update}
>
{ etc... }
</Mutation>
}
}
类组件扩展React.Component{
更新=(u)=>this.props.update;
渲染(){
返回
{等等..}
}
}
您提到的答案是建议已经有了一个解决方案-使用类方法(例如,在构造函数中绑定或更好的箭头函数作为类属性)