mav*_*ick 4 javascript ecmascript-6 reactjs mobx
我正在创建一个 React 应用程序,它在用户键入时向服务器发出搜索请求。我想消除这个搜索请求,但不确定如何在我现有的代码中实现它:
Mobx 商店:
// function which initiates a fetch request to server
@action searchPlanet = async (event) => {
this.searchString = event.target.value;
this.planets = await getPlanets(this.searchString);
}
Run Code Online (Sandbox Code Playgroud)
反应组件调用searchPlanet:
const Search = observer(({ store }) => {
const planetList = toJS(store.planets);
return (
<div>
<div className={style.search_container}>
<input type="text" id="search" onChange={e => store.searchPlanet(e)} value={store.searchString} placeholder="search planet" />
</div>
</div>
)
})
Run Code Online (Sandbox Code Playgroud)
我不能直接使用 debounce 函数,onChange因为这也会延迟 Search 组件的重新渲染,所以用户会在一段时间后看到输入的文本。但是我不知道如何在我的商店中实现去抖动功能?我可以做这样的事情:
import _ from lodash
@action searchPlanet = async (event) => {
this.searchString = event.target.value;
this.planets = await getPlanets(this.searchString);
}
debounceSearch = _.debounce(this.searchPlanet, 250);
Run Code Online (Sandbox Code Playgroud)
问题是由于上述原因,我无法debounceSearch直接从Search组件调用。但是我想getPlanetsdebounce 函数,它返回一个promise(我不确定Lodash debounce 函数是否可以返回包装函数返回的promise)?
您可以在 debounced 函数中执行此操作,而不是planets在您的searchPlanet操作中为其分配值。
例子
@observer
class App extends Component {
@observable value = "";
@observable query = "";
onChange = action(event => {
const { value } = event.target;
this.value = value;
this.search(value);
});
search = debounce(action(query => {
this.query = query;
}), 250);
render() {
const { value, query, onChange } = this;
return (
<div>
<input value={value} onChange={onChange} />
<div>{query}</div>
</div>
);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3918 次 |
| 最近记录: |