我的组件应用
import React, { Component } from "react";
import City from "./City";
import withDataLoader from "./withDataLoader";
const App = () => {
const MyCity = withDataLoader(
City,
"https://5e5cf5eb97d2ea0014796f01.mockapi.io/api/v1/cities/1"
);
return (
<div className="page">
<MyCity />
</div>
);
};
export default App;
我的高阶组件
import React from "react";
import Spinner from "./Spiner";
const withDataLoader = (url, Component) => {
class Container extends React.Component {
state = "";
componentDidMount() {
this.get();
}
get = () => {
fetch(url)
.then((response) => response.json())
.then((data) => this.setState(data));
};
render() {
return this.state === "" ? <Spinner /> : <Component data={this.state} />;
}
};
return Container
};
export default withDataLoader;
我将参数传递给HOC
withDataLoader(url, City)
但是在文档中我看到了另一个条目
withDataLoader(url)(City)
https://ru.reactjs.org/docs/higher-order-component ...
如何做到这一点,以便您可以通过DataLoader(url)(City)将参数传递给飞节?
答案 0 :(得分:0)
从withDataLoader(url, City)
到withDataLoader(url)(City)
的切换称为currying。
// Change function declaration
const withDataLoader = (url, Component) => {}
|
v
const withDataLoader = (url) => (Component) => {}
请注意,您可能在函数调用中放置了错误的值:
// Instead (City,URL)
const MyCity = withDataLoader("https://...",City)
答案 1 :(得分:0)
I solved the problem this way
const withDataLoader = (url) => {
return function (Component) {
return class Container extends React.Component {
state = "";
componentDidMount() {
this.get();
}
get = () => {
fetch(url)
.then((response) => response.json())
.then((data) => this.setState(data));
};
render() {
return this.state === "" ? (
<Spinner />
) : (
<Component data={this.state} />
);
}
};
};
};