为什么 Reactjs 必须重用 HOC 中的代码?
Why Reactjs has to reuse code in HOC?
我想要的只是 运行 一段 javascript 代码来查询后端 GraphQL 服务器。为什么我必须将查询包装在 HOC 组件中?就像 this document 中所说的那样。
import { Query } from "react-apollo";
import gql from "graphql-tag";
const ExchangeRates = () => (
<Query
query={gql`
{
rates(currency: "USD") {
currency
rate
}
}
`}
>
{({ loading, error, data }) => {
if (loading) return <p>Loading...</p>;
if (error) return <p>Error :(</p>;
return data.rates.map(({ currency, rate }) => (
<div key={currency}>
<p>{`${currency}: ${rate}`}</p>
</div>
));
}}
</Query>
);
看起来很笨拙的解决方案?为什么一定要这样?它会使事情变得更容易还是更困难?它背后的理念是什么?
更新:
有一点很麻烦:我只想调用一个 API 调用,它是不可见的,为什么我必须在 render() 函数中渲染一个标签? API 呼叫根本不应该是可见的。这种扭曲让我觉得整个 HOC 的事情都是 hack,假的。你怎么看?
他们使用 Render Prop Pattern
是因为它具有高度声明性,如概述 here
This encapsulation makes composing your Query components with your presentational components a breeze
现在关于 Render Prop
本身,根据官方反应 docs
The term “render prop” refers to a simple technique for sharing code between React components using a prop whose value is a function.
A component with a render prop takes a function that returns a React element and calls it instead of implementing its own render logic.
如前所述here这种技术是 React 处理横切关注点的首选方法。
Components are the primary unit of code reuse in React, but it’s not a always obvious how to share the state or behavior that one component encapsulates to other components that need that same state.
因此,对于 render prop
,您只输出要与其他组件共享的封装状态的 public 结果。
render prop
不是 HoC
,而是它的替代品,最近被 React 团队本身接受。
我想要的只是 运行 一段 javascript 代码来查询后端 GraphQL 服务器。为什么我必须将查询包装在 HOC 组件中?就像 this document 中所说的那样。
import { Query } from "react-apollo";
import gql from "graphql-tag";
const ExchangeRates = () => (
<Query
query={gql`
{
rates(currency: "USD") {
currency
rate
}
}
`}
>
{({ loading, error, data }) => {
if (loading) return <p>Loading...</p>;
if (error) return <p>Error :(</p>;
return data.rates.map(({ currency, rate }) => (
<div key={currency}>
<p>{`${currency}: ${rate}`}</p>
</div>
));
}}
</Query>
);
看起来很笨拙的解决方案?为什么一定要这样?它会使事情变得更容易还是更困难?它背后的理念是什么?
更新:
有一点很麻烦:我只想调用一个 API 调用,它是不可见的,为什么我必须在 render() 函数中渲染一个标签? API 呼叫根本不应该是可见的。这种扭曲让我觉得整个 HOC 的事情都是 hack,假的。你怎么看?
他们使用 Render Prop Pattern
是因为它具有高度声明性,如概述 here
This encapsulation makes composing your Query components with your presentational components a breeze
现在关于 Render Prop
本身,根据官方反应 docs
The term “render prop” refers to a simple technique for sharing code between React components using a prop whose value is a function.
A component with a render prop takes a function that returns a React element and calls it instead of implementing its own render logic.
如前所述here这种技术是 React 处理横切关注点的首选方法。
Components are the primary unit of code reuse in React, but it’s not a always obvious how to share the state or behavior that one component encapsulates to other components that need that same state.
因此,对于 render prop
,您只输出要与其他组件共享的封装状态的 public 结果。
render prop
不是 HoC
,而是它的替代品,最近被 React 团队本身接受。