我试图了解Reacts状态,并且我想知道这是否是预期的行为。
所以我有一个表单并在表单上提交我触发一个函数,这个函数接受一个地址并将其转换为lat和lng并将其吐入一个json fetch调用,该调用获取一个地图的标记位置。
我注意到的是,当我在控制台中记录标记时,表单提交首先记录旧对象,然后记录它返回的新对象,每次进行表单提交时都会这样做。这是正常的吗?当我在函数中的console.log时,我只得到旧状态。
这是我的代码:http://pastiebin.com/embed/5a8da508b22c8
更新:将代码添加到网站而不是粘贴bin:
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;