Я разрабатываю приложение о поездках с набором путевых точек. Я определил поездки только с двумя путевыми точками:
interface Waypoint{
lat: string,
lon: string,
displayName: string,
departureDate: string;
}
interface Trip{
tripId: string;
waypoints: Waypoint[];
completed: boolean;
}
constructor(props: PropsType) {
super(props);
this.state = {
// other state variables
trip: {
waypoints: [{lat:'', lon:'', displayName:'', departureDate: ''},
{lat:'', lon:'', displayName:'', departureDate: ''}],
tripId: this.props.location.state.trip.id || '',
completed: this.props.location.state.trip.completed || false,
},
};
}
При обновлении поля состояния this.state.trip.waypoints[i].address
, если я использую метод .map()
, все поля обновляются, тогда как когда я ищу конкретный c индекс, только это индекс обновлен. Параметр input
- текстовое содержимое в поле ввода. Допустим, я пишу «берлин» в поле ввода:
handleInputChange = (input: string, index: number = 0) => {
this.setState((prevState) => {
console.log('init: ', prevState.trip.waypoints)
const wps = prevState.trip.waypoints.map((wp, i) => {
console.log('string ' + i.toString(), wp.displayName)
if (index === i) {
wp.displayName = input;
return wp;
} else {
return wp;
}
});
console.log('stateWps: ', wps)
return {
trip: {
...prevState.trip,
waypoints: wps,
}
};
});
}
Имеет такой эффект при написании последней буквы, во всех случаях обновляются обе путевые точки:
![enter image description here](https://i.stack.imgur.com/RPNDr.png)
Reading the state.trip updates all the waypoints before enetring the .map()
method. Updating the first array index automatically updates the second one. However if I update the state in the following manner I do not have this behaviour:
handleInputChange = (input: string, index: number = 0) => {
const wps = [...this.state.trip.waypoints];
wps[index] = {...wps[index], displayName: input};
this.setState({
trip: {
...this.state.trip,
waypoints: wps
}
}, () => {
console.log('stateWps ', this.state.trip.waypoints)
})
}
Yields this output:
![ArrayIndex](https://i.stack.imgur.com/JQMt9.png)
How can be the first handleInputChange
function be re-written to update the state.trip.waypoints
using the .map()
method? Thanks
Update:
I do not think the prblem should be here since using the other way it is working as expected, it is when using prevState and the .map()
method that it updates all the waypoints.displayName fields
even when I hard-code the 0
value in the function call. Just in case you find anything.
The component handling the input:
{
this.handleInputChange(input, 0);
}}
/>
class AutosuggestInput extends React.Component:
onInputHandler = (event: FormEvent, {newValue, method}: {newValue: string; method: string}) => {
event.preventDefault();
this.props.onValueChange(newValue);
};
...
render() {
const { value, suggestions, placeholder } = this.props;
const inputProps = {
placeholder: placeholder ? placeholder : '',
value: value ? value : '',
onChange: this.onInputHandler
};
return (
);
}
I am using react-autosuggest: https://github.com/moroshko/react-autosuggest