【发布时间】:2018-04-20 21:21:01
【问题描述】:
可能是一个新手问题。我是新手。
根据一些博客文章等,我能够构建一个页面,该页面包含高阶组件和 componentDidMount 以从 API 加载数据并将其呈现到页面。它工作得很好,代码看起来很干净,但我不知道如何通过高阶组件传递某种 onClick,最终我想将 fetch 的内容移到一个可以调用的函数中componentDidMount 和 <Button onClick={}>Reload</Button>。哈普请
import React, { Component } from 'react';
import {Button, CardColumns, Card, CardHeader, CardBody} from 'reactstrap';
const API = 'http://localhost:3000/';
const DEFAULT_QUERY = 'endpoint';
const withFetching = (url) => (Comp) =>
class WithFetching extends Component {
constructor(props) {
super(props);
this.state = {
data: {},
isLoading: false,
error: null,
};
// Goes here?
this.onClick = () => {
console.log("Handled!");
};
}
componentDidMount() {
this.setState({ isLoading: true });
fetch(url)
.then(response => {
if (response.ok) {
return response.json();
} else {
throw new Error('Something went wrong ...');
}
})
.then(data => this.setState({ data, isLoading: false }))
.catch(error => this.setState({ error, isLoading: false }));
}
// Or here maybe??
this.onClick = () => {
console.log("Handled!");
};
render() {
// How do I pass it in?
return <Comp { ...this.props } { ...this.state } onClick={this.onClick} />
}
}
// How do I tell this component to expect it to recieve the handler?
const App = ({ data, isLoading, error }) => {
const hits = data.hits || [];
console.log(data);
if (error) {
return <p>{error.message}</p>;
}
if (isLoading) {
return <p>Loading ...</p>;
}
return (
<div className="animated fadeIn">
<CardColumns className="cols-2">
<Card>
<CardHeader>
API Card!
<div className="card-actions">
</div>
</CardHeader>
<CardBody>
{hits.map(hit =>
<div key={hit.foo}>
<h3>{hit.foo}</h3>
_____
</div>
)}
<Button onClick={props.onClick}>Launch demo modal</Button>
</CardBody>
</Card>
</CardColumns>
</div>
);
}
export default withFetching(API + DEFAULT_QUERY)(App);
Here 是引导我了解我正在使用的架构的博客文章:
编辑:我可以在类之外创建一个函数,以便它在任何地方都可用,但我最初想将它留在 in 的原因是我实际上可以更改状态并重新渲染带有新数据的卡。试图找出正确使用bind() 来完成这项工作...... JS 有时让我觉得很愚蠢:p
【问题讨论】:
-
您可以将 onlcick 函数作为道具传递
-
正确的语法是什么?
-
@mohhamad-hasham - 这似乎是正确的答案,但我无法坚持做对。有什么建议吗?
-
你能说出哪里不对吗?这样我就可以帮助你!
标签: javascript reactjs higher-order-components