简体   繁体   中英

React functional component using the `useState` hook does not update onChange using ReactiveSearch

I am trying to use the ReactiveSearch component library to build a basic search application, and need to use the components as controlled component ( https://reactjs.org/docs/forms.html ). For all of the other filters I am working with, this is no problem, and the app detects changes and updates accordingly. However, for this DateRange component, it won't work. My working hypothesis is that it has something to do with the state value being an object rather than an array, but I can't find evidence to support that yet.

I've also tried using a regular class component, with the same result.

Link to Sandbox: https://codesandbox.io/s/ecstatic-ride-bly6r?fontsize=14&hidenavigation=1&theme=dark

Basic code snippet with no other filters

import React, { useState } from "react";
import {
  ReactiveBase,
  ResultsList,
  DateRange,
  SelectedFilters
} from "@appbaseio/reactivesearch";

const App = props => {
  const [filterState, setFilterState] = useState({
    DateFilter: { start: new Date(), end: new Date() }
  });
  return (
    <div className="App">
      <ReactiveBase
        app="good-books-ds"
        credentials="nY6NNTZZ6:27b76b9f-18ea-456c-bc5e-3a5263ebc63d"
      >
        <DateRange
          value={filterState.DateFilter}
          onChange={value => {
            setFilterState({
              ...filterState,
              DateFilter: {
                start: value.start,
                end: value.end
              }
            });
          }}
          componentId="DateFilter"
          dataField="timestamp"
        />
        <SelectedFilters />
      </ReactiveBase>
    </div>
  );
};

export default App;

Just changing value to defaultValue worked for me ( https://codesandbox.io/s/jolly-spence-1o8bv ).

    <DateRange
      defaultValue={filterState.DateFilter}
      onChange={value => {
        setFilterState({
          DateFilter: {
            start: value.start,
            end: value.end
          }
        });
      }}
      componentId="DateFilter"
      dataField="timestamp"
    />

I also removed the DateFilter spread in your setFilterState , since your previous state was being fully overwritten regardless.

It turned out to be an underlying problem with how the ReactiveSearch library was comparing the dates, as well as not setting values properly. Will make a PR to fix it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM