我的自动完成包没有更新状态。

huangapple go评论157阅读模式
英文:

My autocomplete package doesn't update the state

问题

以下是您要翻译的代码部分:

  1. // 使用 Algolia Places 自动完成地址输入。
  2. // 然而,当我检查组件的状态时,我发现点击按钮后,即使字段内的文本发生更改,状态也没有更新。
  3. // 我不明白,为什么不起作用,因为我已经正确设置了 handleChange 函数。
  4. export function handleChange(event) {
  5. const target = event.target;
  6. const value = target.type === 'checkbox' ? target.checked : target.value;
  7. const name = target.name;
  8. this.setState({
  9. [name]: value
  10. });
  11. }
  12. export function addAlgolia() {
  13. var places = require('places.js');
  14. var placesAutocomplete = places({
  15. appId: "APPID",
  16. apiKey: "APIKEY",
  17. container: document.querySelector('#address-input')
  18. });
  19. }

示例输入代码:

  1. import React, { Component } from 'react'
  2. import { withRouter } from 'react-router-dom'
  3. import Dashboard from '../Dashboard'
  4. import Axios from 'axios'
  5. import * as Cookies from 'js-cookie'
  6. import ErrorContainer from '../../components/ErrorContainer'
  7. import { addAlgolia, handleChange } from 'utils'
  8. export class OrganismSettings extends Component {
  9. constructor(props) {
  10. super(props);
  11. this.state = { loading: true, organism: [], name: "", description: "", address: "", picture: null }
  12. this.getOrganism = this.getOrganism.bind(this);
  13. this.handleChange = handleChange.bind(this);
  14. this.handleSubmit = this.handleSubmit.bind(this);
  15. this.handleChangePicture = this.handleChangePicture.bind(this);
  16. }
  17. componentDidMount() {
  18. this.getOrganism();
  19. addAlgolia()
  20. }
  21. // ... 省略了其他方法和渲染部分 ...
  22. }
  23. export default withRouter(OrganismSettings)
英文:

I use Algolia Places to autocomplete my address input.
However, when I check the state of my component, I can see that clicking on the button, even if the text changes inside the field, doesn't update the state.
I don't get it, why it doesn't work, since I setup my handleChange function correctly.

  1. export function handleChange(event) {
  2. const target = event.target;
  3. const value = target.type === 'checkbox' ? target.checked : target.value;
  4. const name = target.name;
  5. this.setState({
  6. [name]: value
  7. });
  8. }
  9. export function addAlgolia() {
  10. var places = require('places.js');
  11. var placesAutocomplete = places({
  12. appId: "APPID",
  13. apiKey: "APIKEY",
  14. container: document.querySelector('#address-input')
  15. });
  16. }

Example code for input :

  1. import React, { Component } from 'react'
  2. import {withRouter} from 'react-router-dom'
  3. import Dashboard from '../Dashboard'
  4. import Axios from 'axios'
  5. import * as Cookies from 'js-cookie'
  6. import ErrorContainer from '../../components/ErrorContainer'
  7. import { addAlgolia, handleChange } from 'utils'
  8. export class OrganismSettings extends Component {
  9. constructor(props) {
  10. super(props);
  11. this.state = {loading: true, organism: [], name: "", description: "", address: "", picture: null}
  12. this.getOrganism = this.getOrganism.bind(this);
  13. this.handleChange = handleChange.bind(this);
  14. this.handleSubmit = this.handleSubmit.bind(this);
  15. this.handleChangePicture = this.handleChangePicture.bind(this);
  16. }
  17. componentDidMount() {
  18. this.getOrganism();
  19. addAlgolia()
  20. }
  21. getOrganism() {
  22. Axios.get('http://localhost:8000/api/organism/settings', {headers: {Accept: 'application/json', Authorization: 'Bearer ' + Cookies.get('token')}})
  23. .then((success) => {
  24. var organism = success.data.data.organism;
  25. this.setState({organism: success.data.data.organism, loading: false})
  26. this.setState({name: organism.name, description: organism.description, address: organism.address})
  27. }, (error) => {
  28. this.props.history.push('/organisme/creation')
  29. })
  30. }
  31. handleChangePicture(event) {
  32. this.setState({picture: event.target.files[0]})
  33. }
  34. handleSubmit(e) {
  35. e.preventDefault();
  36. var formData = new FormData();
  37. formData.append('name', this.state.name);
  38. formData.append('description', this.state.description);
  39. formData.append('address', this.state.address);
  40. formData.append('picture', this.state.picture);
  41. formData.append('_method', 'PATCH');
  42. var token = Cookies.get('token');
  43. Axios.post('http://localhost:8000/api/organism/settings', formData, {
  44. headers: {
  45. "Accept": 'application/json',
  46. "Authorization": `Bearer ${token}`,
  47. }
  48. }).then(
  49. (success) => {
  50. this.setState({loading: false});
  51. //this.props.history.push('/organisme')
  52. }, (error) => {
  53. this.setState({errors : error.response.data.data})
  54. if(error.response.data.redirect != "") {
  55. this.props.history.push(error.response.data.redirect)
  56. }
  57. }
  58. )
  59. }
  60. render() {
  61. return (
  62. <Dashboard loading={this.state.loading}>
  63. <section className="section has-text-centered">
  64. <div className="column is-offset-1 is-10">
  65. <h1 className="title is-size-1 register-title">Paramètres de {this.state.name}</h1>
  66. <section className="section organism-register">
  67. <form encType="multipart/form-data" className="user-form fullbox-form" method="POST" onSubmit={this.handleSubmit}>
  68. <div className="has-text-left input-fixer">
  69. <label className="is-size-4">Nom de l'organisme : </label><input type="text" name="name" placeholder="Nom de l'organisme" value={this.state.name} onChange={this.handleChange}/>
  70. <label className="is-size-4">Description de l'organisme : </label><textarea name="description" placeholder="Description de l'organisme" value={this.state.description} onChange={this.handleChange}/>
  71. <label className="is-size-4">Adresse de l'organisme : </label><input id="address-input" type="text" name="address" value={this.state.address} onChange={this.handleChange}></input>
  72. <label className="is-size-4">Ajouter le logo de votre organisme : </label>
  73. <input type="file" name="picture" onChange={this.handleChangePicture} />
  74. </div>
  75. <ErrorContainer errors={this.state.errors} />
  76. <button className="button is-primary has-text-left">Soumettre les changements</button>
  77. </form>
  78. </section>
  79. </div>
  80. </section>
  81. </Dashboard>
  82. )
  83. }
  84. }
  85. export default withRouter(OrganismSettings)

答案1

得分: 0

Algolia Places会仅更新输入的一个值,因此您需要自行添加与状态的同步。最佳方案是使用库提供的事件:

https://community.algolia.com/places/documentation.html#events

在您的代码中:

  1. export function addAlgolia() {
  2. var places = require('places.js');
  3. var placesAutocomplete = places({
  4. appId: "APPID",
  5. apiKey: "APIKEY",
  6. container: document.querySelector('#address-input')
  7. });
  8. placesAutocomplete.on('change', e => {
  9. const value = e.suggestion;
  10. // 在这里,您需要调用类似 this.setState(...) 的内容,将“value”传递给您的主要组件
  11. });
  12. }
英文:

Algolia Places updates just a value of the input, so You have to add synchronization with state on Your own.

The best fit would be to use events provided by the library:

https://community.algolia.com/places/documentation.html#events

in Your code:

  1. export function addAlgolia() {
  2. var places = require('places.js');
  3. var placesAutocomplete = places({
  4. appId: "APPID",
  5. apiKey: "APIKEY",
  6. container: document.querySelector('#address-input')
  7. });
  8. placesAutocomplete.on('change', e => {
  9. const value = e.suggestion;
  10. // here You have to call something like this.setState(...) with "value" for Your main component
  11. });
  12. }

huangapple
  • 本文由 发表于 2020年1月6日 23:35:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/59614844.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定