【发布时间】:2019-10-30 18:49:01
【问题描述】:
React Native 将 this.state.input 存储为未定义的工作在 React Native Web 中被罚款
我已经做了一段时间的 react 开发人员,想要构建一个简单的应用程序,使用 react native 和一些网络组件被卡住试图弄清楚为什么 this.state.input 被存储为一个未定义的原始值新的 react我的反应知识可能会影响我的观点
使用 axios 的 https 发布请求也可以正常工作,但一直存储为未定义
顺便说一句,我在 stackoverflow 中搜索了一个解决方案,尝试了我能找到的每一个模糊的解决方案,所以这不太可能是一个重复的问题
不知道是生命周期问题还是绑定问题,还是 react-native api 问题好像搞不明白
import React, {Component} from 'react';
import axios from 'axios';
import {View, Text, TextInput, Button, StyleSheet} from 'react-native';
class App extends Component {
constructor(props) {
super(props);
this.state = {
input: '',
messages: '',
};
this.handleChange = this.handleChange.bind(this);
this.sendMessage = this.sendMessage.bind(this);
}
handleChange(event) {
this.setState({
input: event.target.value,
});
}
sendMessage() {
const sendIt = `${this.state.input}`;// this.state.input RETRIEVED AND STORED AS UNDEFINED
const todol = {
todo: `${sendIt}`,
};
console.log(sendIt); // GETTING UNDEFINED HERE WORKS FINE WITH REACT NATIVE WEB
axios
.post('http://10.120.1.190:7000/todos/add', todol)
.then(res => {
this.setState({messages: JSON.stringify(res.data)});
console.log(this.state.messages);
})
.catch(err => console.log(`${err}`));
this.setState({
input: '',
});
}
render() {
return (
<View>
<Text style={styles.old}>Type in a new Message:</Text>
<TextInput
style={styles.old}
value={this.state.input}
onChange={this.handleChange}
/>
<Button title="Submit" onPress={this.sendMessage}></Button>
<Text>{this.state.messages}</Text>
</View>
);
}
}
// Change code above this line
const styles = StyleSheet.create({
old: {
fontFamily: 'Helvetica',
fontSize: 15,
lineHeight: 30,
margin: 'auto',
},
new: {
fontFamily: 'Lato',
fontSize: 25,
lineHeight: 30,
margin: 'auto',
},
});
export default App;
【问题讨论】:
标签: javascript reactjs react-native mobile