在读取React中的状态-打字稿

时间:2020-07-14 07:43:17

标签: arrays reactjs typescript state setstate

我正在开发有关旅行的应用程序,其中包含一组航路点。我只用两个航点定义了行程:

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()方法,则所有字段都会更新,而当我查找特定索引时,只会更新该索引。 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

读取state.trip会更新所有航路点,然后再进入.map()方法。更新第一个数组索引会自动更新第二个数组索引。但是,如果我以以下方式更新状态,则不会有此行为:

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)
    })
}

提供此输出:

ArrayIndex

如何使用handleInputChange方法重写第一个state.trip.waypoints函数以更新.map()?谢谢

更新:

我不认为问题应该在这里,因为使用其他方式可以按预期方式工作,正是在使用prevState和.map()方法时,即使我辛苦了也会更新所有waypoints.displayName fields对函数调用中的0值进行编码。万一您发现任何东西。 处理输入的组件:

<AutosuggestInput
    placeholder="Trip Origin"
    value={this.state.trip.waypoints[0].displayName}
    suggestions={places}
    onValueChange={(input: string) => {
        this.handleInputChange(input, 0);
    }}
/>

AutosuggestInput类扩展了React.Component

onInputHandler = (event: FormEvent<any>, {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 (
  <Autosuggest
    suggestions={suggestions}
    onSuggestionsFetchRequested={this.onSuggestionsFetchRequested}
    onSuggestionsClearRequested={this.onSuggestionsClearRequested}
    getSuggestionValue={this.getSuggestionValue}
    renderSuggestion={renderSuggestion}
    inputProps={inputProps}
  />
);

}

我正在使用react-autosuggest:https://github.com/moroshko/react-autosuggest

0 个答案:

没有答案