在ReactJS / Redux中实现AutoComplete,并且不改变搜索值,可以使用以下解决方法:
首先,创建一个Redux store来存储搜索相关的数据。可以使用redux-thunk中间件来处理异步操作。
在Redux store中,创建以下reducer来处理搜索相关的操作:
// actionTypes.js
export const SET_SEARCH_TERM = 'SET_SEARCH_TERM';
export const SET_SEARCH_RESULTS = 'SET_SEARCH_RESULTS';
// actions.js
import { SET_SEARCH_TERM, SET_SEARCH_RESULTS } from './actionTypes';
export const setSearchTerm = searchTerm => ({
type: SET_SEARCH_TERM,
payload: searchTerm
});
export const setSearchResults = results => ({
type: SET_SEARCH_RESULTS,
payload: results
});
// reducer.js
import { SET_SEARCH_TERM, SET_SEARCH_RESULTS } from './actionTypes';
const initialState = {
searchTerm: '',
searchResults: []
};
const reducer = (state = initialState, action) => {
switch (action.type) {
case SET_SEARCH_TERM:
return {
...state,
searchTerm: action.payload
};
case SET_SEARCH_RESULTS:
return {
...state,
searchResults: action.payload
};
default:
return state;
}
};
export default reducer;
然后,在React组件中,使用redux-thunk来调用异步操作,并将搜索结果存储到Redux store中:
import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { setSearchTerm, setSearchResults } from './actions';
const AutoComplete = () => {
const dispatch = useDispatch();
const searchTerm = useSelector(state => state.searchTerm);
const searchResults = useSelector(state => state.searchResults);
const handleSearch = async () => {
// 进行搜索操作,将结果存储到searchResults中
const results = await fetchSearchResults(searchTerm);
dispatch(setSearchResults(results));
};
useEffect(() => {
handleSearch();
}, [searchTerm]);
const handleChange = e => {
dispatch(setSearchTerm(e.target.value));
};
return (
{searchResults.map(result => (
- {result.name}
))}
);
};
export default AutoComplete;
在上述代码中,AutoComplete组件中的输入框的值由Redux store中的searchTerm来控制,并且每当searchTerm改变时,会触发handleSearch函数来调用异步操作并更新搜索结果。
这样,无论是用户输入还是调用异步操作,都不会直接改变搜索值,而是通过Redux store来管理和更新搜索值。