0

我试图了解 Reacts 状态,我想知道这是否是预期的行为。

所以我有一个表单,在表单提交时我触发了一个函数,这个函数接受一个地址并将其转换为 lat 和 lng 并将其吐出到一个 json fetch 调用中,该调用获取地图的一些标记位置。

我注意到的是,当我 console.log 渲染表单提交中的标记时,首先记录旧对象,然后记录它返回的新对象,每次提交表单时都会这样做。这是正常的吗?当我在函数中 console.log 时,我只会得到旧状态。

这是我的代码: http: //pastiebin.com/embed/5a8da508b22c8

更新:将代码添加到站点而不是 pastebin:

import React from "react";
import MapsJson from './MapsJson';

class Maps extends React.Component {

    constructor(props) {
       super(props);
        this.state  = {
            lat: '51.507351',
            lng: '-0.127758',
            month: '07',
            year: '2017',
        };
        this.submitHandler = this.submitHandler.bind(this)
    }

    submitHandler(e) {

        e.preventDefault();
        if (e.target.place.value) {
            var removeError = document.getElementById("error");
            while (removeError.firstChild) {
                removeError.removeChild(removeError.firstChild);
            }
            let self = this;
            let geocoder = new window.google.maps.Geocoder();
            let getYear = e.target.year.value;
            let getMonth = e.target.month.value;
            geocoder.geocode( { 'address': e.target.place.value + ', UK'}, function(results, status) {
                if (status === 'OK') {
                    self.setState({
                        lat: results[0].geometry.location.lat(), 
                        lng: results[0].geometry.location.lng(), 
                        year: getYear,
                        month: getMonth                    },
                    function () {
                        self.getArea(this.state.lat, this.state.lng, this.state.year, this.state.month);                                            
                    })
                } else {
                    console.log('Geocode was not successful for the following reason: ' + status);
                }
            });
        } else {

            if (document.getElementById('error').innerHTML === 'A place is needed') {

            } else {
                document.getElementById('error').innerHTML += 'A place is needed';
                console.log('need a place');
            }
        }

     }



    changeHandler(e) {
        // console.log(`name and value: `, e.target.name, e.target.value)
        //console.log('triggered5')
    }

    componentWillMount() {
        this.setState({ markers: [] })
    }

    componentDidMount() {
        this.getArea(this.state.lat, this.state.lng, this.state.year, this.state.month)

    }


    getArea(lat, lng, year, month, nextProps) {
        const url = [
        // Length issue
            `https://data.police.uk/api/crimes-street/all-crime?lat=${lat}&lng=${lng}&date=${year}-${month}`
        ].join("")

        fetch(url)
          .then(res => res.json())
          .then(data => {
            this.setState({ markers: data });
        });    
    }


  render() {
    console.log(this.state.markers)
    return (
        <div>
            <div id="crimeCount"></div>
            <form onSubmit={this.submitHandler}>
                <input onChange={this.changeHandler} type='text' name='place' placeholder='Enter a place' />
                <div id="error"></div>
                <select name='month'>
                    <option value="01">01</option>
                    <option value="02">02</option>
                    <option value="03">03</option>
                    <option value="04">04</option>
                    <option value="05">05</option>
                    <option value="06">06</option>
                    <option value="07">07</option>
                    <option value="08">08</option>
                    <option value="09">09</option>
                    <option value="10">10</option>
                    <option value="11">11</option>
                    <option value="12">12</option>
                </select>
                <select name='year'>
                  <option value="2017">2017</option>
                  <option value="2016">2016</option>
                  <option value="2015">2015</option>
                </select>
                <input type='submit' value='submit' />
            </form>
        </div>
    )

  }
}

export default Maps;
4

0 回答 0