reactjs - 只是在父组件中进行查询而不渲染任何东西并将所有数据作为道具发送
问题描述
我想在我的父组件中进行一个查询,而不是渲染任何东西并将该数据传递给某个子组件。我们如何在 react 和 graphql 中实现这一点?
{
({loading,error,data}) =>{
if(loading) return <h4>Loading...</h4>
if(error) console.log(error)
console.log("graphql data is ",data);
return(
<div className="body">
</div>
</div>
);
}
}
</Query>
我想在我的父组件中进行此查询并将其作为子组件传递。如果是简单的 api,我可以简单地调用 api 并将其存储在我的 redux 中,然后将这些数据作为子属性获取。如何在不渲染任何东西的情况下实现相同的目标?
解决方案
你可以创建一个组件来渲染它的子组件。这是一个如何在反应中做到这一点的示例。
像这样的东西。
class Query extends Component {
state = {
loading: true,
error: {},
data: {}
}
componentDidMount() {
//do the apicall here
this.setState({ loading: false, data: { header: "may the force be with you" } });
}
render() {
const { state: props, props: { children } } = this;
// return the data here
// passing state as props here after renaming state to props
return children(props);
}
}
使用反应状态而不是 redux。如果你想使用 redux,你可以制作这个连接的组件。并且像这样使用组件。
<Query>
{
({ loading, error, data }) => {
if (loading) return <>Loading.......</>
if (Object.keys(error).length > 0) return <>Some Error Handler</>
if (data) return (
<>
<img src={logo} className="App-logo" alt="logo" />
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
{data.header}
</a>
</>
)
}
}
</Query>
推荐阅读
- json - 从字典列表创建数据帧格式错误的列表错误
- typescript - 是否可以在打字稿中限制推断的泛型?
- visual-studio-code - 我无法使用 Jupyter 在 VScode 上显示来自 Julia 的“readline”函数的输出
- javascript - 有人可以告诉我有什么问题吗?
- python - 在数据框中获取 json 值
- arrays - 搜索 PostgreSQL 数组列
- javascript - 包裹在 div 中的 span 元素之间不需要的空格
- dataframe - PySpark / Spark SQL DataFrame - 当数据为空时解析结构类型时出错
- sql - 根据匹配的客户字段(电话、电子邮件、地址)为客户分配 home_id - 重复问题
- reactjs - 将 React 类组件转换为函数组件