react-apollo - 如何从包装组件设置查询变量?

时间:2017-02-21 17:29:20

标签: reactjs react-apollo apollo-client

react-apollo提供了将组件道具转换为查询变量的功能:

<MyComponentWithData propsForQueryVariables={...} />

但我需要使用包装组件中的变量开始查询。

类似的东西:

class MyComponent extends React.Component {
   //...
   onReady() {
     // should be first request to server
     this.props.refetch({
       // variables here
     })
   }

   onFilterChanged() {
     this.props.refetch({
       // new variables here
     })
   }
}

const MyComponentWithData = graphql(QUERY, {
  options: {
    waitUntilComponentStartQuery: true
    // pollInterval:...
  },
  props({ data: { items, refetch } }) {
    return {
      items: items,
      refetch: refetch
    };
  }
})(MyComponent);

更新

QUERY的{​​p> MyComponent看起来像

query getItems($filter: JSON!) {
 items(filter: $filter) {
  id
  name
 } 
}

filter 不可为空。因此第一个请求应该具有有效变量filter,并且应该在包装组件中创建此变量。

2 个答案:

答案 0 :(得分:4)

您可以将父道具传递给graphql HoC中初始提取的变量,如下所示:

ParentComponent.jsx

import ChildComponent from './ChildComponent';

const ParentComponent = () => <ChildComponent filterPropValue="myDefaultFilterValue" />;

export default ParentComponent;

ChildComponent.jsx

class ChildComponent extends React.Component {
  refresh() {
    this.props.refetch({
      filter: 'mynewFilterValue'
    });
  }

  render() {
    return (
      <div>I am a child component with {this.props.items.length} items.</div>
    );
  }
}

export default graphql(MyQuery, {
  options: (props) => ({
    variables: {
      filter: props.filterPropValue
    }
  }),
  props: ({ data: { items, error, refetch }) => ({
    items,
    error,
    refetch
  })
})(ChildComponent);

然后可以通过refetch()处理任何带有新参数的后续反映。

答案 1 :(得分:1)

package com.example.sasse.myapplication; import android.*; import android.Manifest; import android.content.pm.PackageManager; import android.location.Location; import android.os.Build; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v4.app.FragmentActivity; import android.os.Bundle; import android.support.v4.content.ContextCompat; import android.util.Log; import android.widget.Toast; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks; import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener; import com.google.android.gms.location.LocationListener; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationServices; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; public class MapsActivity extends FragmentActivity implements LocationListener, ConnectionCallbacks, OnConnectionFailedListener, OnMapReadyCallback { private static final String TAG = "MapsActivity"; private GoogleMap mMap; protected GoogleApiClient mGoogleApiClient; protected LocationRequest mLocationRequest; public int clock = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { checkLocationPermission(); } } @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; // Add a marker in Sydney and move the camera LatLng sydney = new LatLng(-34, 151); mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney")); mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney)); //Initialize Google Play Services if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { buildGoogleApiClient(); mMap.setMyLocationEnabled(true); } } else { buildGoogleApiClient(); mMap.setMyLocationEnabled(true); } } public void onLocationChanged(Location location) { clock++; if (clock>=10) { Toast.makeText(this, "clock : "+clock, Toast.LENGTH_SHORT).show(); clock=0; } Log.i(TAG, "= = = = = >>> clock : "+clock); } // --------------------------------------------------------------------------------------------- // ---------------- VERIFICAÇÃO DA CONEXÃO COM O SERVIDOR DO GOOGLE MAPS----------------------- // --------------------------------------------------------------------------------------------- public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99; public boolean checkLocationPermission() { if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // Asking user if explanation is needed if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.ACCESS_FINE_LOCATION)) { // Show an explanation to the user *asynchronously* -- don't block // this thread waiting for the user's response! After the user // sees the explanation, try again to request the permission. //Prompt the user once explanation has been shown ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION); } else { // No explanation needed, we can request the permission. ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION); } return false; } else { return true; } } public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) { switch (requestCode) { case MY_PERMISSIONS_REQUEST_LOCATION: { // If request is cancelled, the result arrays are empty. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // permission was granted. Do the // contacts-related task you need to do. if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { if (mGoogleApiClient == null) { buildGoogleApiClient(); } mMap.setMyLocationEnabled(true); } } else { // Permission denied, Disable the functionality that depends on this permission. Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show(); } } // other 'case' lines to check for other permissions this app might request. // You can add here other case statements according to your requirement. } } protected synchronized void buildGoogleApiClient() { mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); mGoogleApiClient.connect(); } public void onConnected(Bundle bundle) { mLocationRequest = new LocationRequest(); mLocationRequest.setInterval(5000); mLocationRequest.setFastestInterval(5000); mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY); if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this); } } public void onConnectionSuspended(int i) { } public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { } } 接受refetch个对象作为参数,请参阅documentation