[英]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 ).我正在尝试使用ReactiveSearch
组件库来构建一个基本的搜索应用程序,并且需要将这些组件用作受控组件( 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.但是,对于这个 DateRange 组件,它不起作用。 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沙盒链接: 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 ).只是将value
更改为defaultValue
对我defaultValue
( 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.我还删除了setFilterState
的DateFilter
传播,因为DateFilter
你之前的状态都被完全覆盖了。
It turned out to be an underlying problem with how the ReactiveSearch library was comparing the dates, as well as not setting values properly.结果证明是 ReactiveSearch 库如何比较日期以及未正确设置值的潜在问题。 Will make a PR to fix it.会做一个 PR 来修复它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.