我正在研究ReactJS,Redux和GraphQL堆栈的ReactJS组件A。
我的数据流是,当用户在另一个组件B上单击某个特定功能的图像时,它会发送一些有关文档的数据,以通过GraphQL在组件A的数据库中获取。
我的困难是,当我单击图像时,我的ReactJS渲染落后一步。技术上是更新的GraphQL状态。
如何使渲染与单击图像的同时触发查询?
这是我的component.js:
import React, { Component } from 'react';
import style from "./Displayer.css";
import client from "apollo-client"
import {graphql, Query} from "react-apollo";
import gql from "graphql-tag";
import equal from 'deep-equal';
class Displayer extends Component {
// some data
backgroundUrl = {
foo
}
recipe; // declare the recipe variable in order to handle the reception on data ulteriously
// my try to render the component immediatly
shouldComponentUpdate (nextProps) {
const currentRecipe = this.props.data.recipe;
const nextRecipe = nextProps.data.recipe;
// deep check if the previous values and next values are similars
// if not, rerender the component
if (!equal(currentRecipe, nextRecipe)) {
if(this.props.data.recipe) {
var {title, description} = this.props.data.recipe
return this.recipe= (
<div className={style.dish_details} >
<p> Title: {title} </p>
<p> Description: {description} </p>
</div>
)
// if there is no recipe data, just display a simple text
}else{
return this.recipe= <div> Here details </div>
}
// if the values are similars don't rerender the component
}else {
return false;
}
}
render() {
return (
<div>
// render the recipe
{this.recipe}
</div>
)
}
}
// set the query
const fetchRecipe = gql`
query recipe($id: String!) {
recipe(id: $id){
title
description
}
}
`;
// bind GraphQL to my component
export default graphql(fetchRecipe,
{options(ownProps) {
return {
variables: { id : ownProps.id} //ownProps.id allow to recuperate the Redux's id's state, to make the recipe query
}
}})(Displayer);
我不知道出什么问题了。如果有人有提示,那就太好了。
答案 0 :(得分:1)
反应中常见的“问题背后的第一步”几乎总是因为您正在访问this.props
而不是nextProps
。如果您用这种方式重写测试该怎么办:
if(nextProps.data.recipe) {
var {title, description} = nextProps.data.recipe
return this.recipe= (
<div className={style.dish_details} >
<p> Title: {title} </p>
<p> Description: {description} </p>
</div>
)
// if there is no recipe data, just display a simple text
}else{
return this.recipe= <div> Here details </div>
}
// if the values are similars don't rerender the component
}else {
return false;
}
?