Javascript 异步-React Select with redux不按时加载选项
我正在尝试将异步react select与redux一起使用,但它无法正常工作。 我从mapStateToProps设置选项,它由函数getPlaces更新 在调用getOptions内部的getPlaces后,OptionState本身会更新,但在getOptions中回调的OptionState会采用以前的值 这是代码 searchForm.js searchReducer.js 我经历了许多类似的问题,但我没有找到答案。Javascript 异步-React Select with redux不按时加载选项,javascript,reactjs,react-redux,react-select,Javascript,Reactjs,React Redux,React Select,我正在尝试将异步react select与redux一起使用,但它无法正常工作。 我从mapStateToProps设置选项,它由函数getPlaces更新 在调用getOptions内部的getPlaces后,OptionState本身会更新,但在getOptions中回调的OptionState会采用以前的值 这是代码 searchForm.js searchReducer.js 我经历了许多类似的问题,但我没有找到答案。 有人能找到我做错了什么吗?渲染相同的值是有意义的-在下一次渲染中,您
有人能找到我做错了什么吗?渲染相同的值是有意义的-在下一次渲染中,您将从存储中获得新选项,因为道具会发生变化并导致新的渲染周期。这就是您应该期望的新值的来源,并呈现again@Gonzalo.-谢谢你的回答。那么,是否不可能从商店获得道具选项?
import { getPlaces, options } from '../../action/searchActions';
const SearchForm = ({getPlaces, options}) => {
console.log(options) // this is updated on time
const [inputValue, setInputValue] = useState('');
const handleInputChange = (newValue: string) => {
const inputValue = newValue.replace(/\W/g, '');
setInputValue(inputValue);
return inputValue;
};
const getOptions = (inputValue, callback) => {
if (!inputValue) {
return callback([]);
}
getPlaces(inputValue)
.then(result=>{
console.log(options)// this shows the previous value
callback(options);
})
};
return (
<div className="search-form-container">
<form noValidate autoComplete="off">
<div className="row">
<AsyncSelect
cacheOptions
loadOptions={getOptions}
defaultOptions
labelKey="PlaceName"
onInputChange={handleInputChange}
filterOption={() => (true)}
className="col-md-3"
/>
</div>
</form>
</div>
)
}
const mapStateToProps = state => ({
options: state.search.options
})
export default connect(mapStateToProps, {getPlaces})(SearchForm);
export const getPlaces = (query) => async dispatch => {
try{
const places = await axios({
url: `/places?query=${query}`,
method: 'GET',
})
const places_data = places.data.Places;
const change_places_format = (places_data) => {
return new Promise((resolve, reject) => {
const new_format_places = places_data.map(place => {
return {
...place,
value: place.PlaceId,
label: place.PlaceName += ` — ${place.CountryName} (${place.PlaceId.replace('-sky', '')})`
}
})
resolve(new_format_places)
});
}
const modified_places = await change_places_format(places_data);
await dispatch({
type: GET_PLACES,
payload: modified_places
})
}catch(err){
dispatch({
type: PLACES_ERROR,
payload: err.response.statusText
})
}
}
const initialState = {
options: [],
loading: false,
error: null
}
export default (state = initialState, action) => {
switch(action.type){
case GET_PLACES:
return{
...state,
options: action.payload,
}
default:
return state;
}
}