你好,我新的反应,我试着玩一点反应,但这里有一点,我不明白。
首先,用返回我的数据的axios数据来获取数据,然后我尝试将它们放入输入字段中,值(并且是只读的),defaultValue更好,现在我有了问题,我什么也没看到,当我用firebug查看时,值是存在的,奇怪的是,当我添加一个不需要的字符时,输入会被我想要的填充,而不是默认的。
很奇怪的是,当我把所有的东西都放在一个数组中,并对它做一个映射函数时,我就得到了一个值
json代码
{"firma":"hallo","strasse":"musterweg 7","plz":"01662"}
js代码
import React from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';
class Testx extends React.Component {
constructor(props) {
super(props);
this.state = {
data:[]
};
}
componentDidMount(){
var self = this;
axios.get('http://localhost/index.php')
.then(function (response) {
self.setState({ data: response.data});
})
.catch(function (error) {
console.log(error);
});
}
render() {
return (
<div>
<input type="text" defaultValue={this.state.data.firma}/>
</div>
);
}
}
ReactDOM.render(<Testx/>, document.getElementById('hello'));
发布于 2017-08-17 09:26:26
您需要等待,直到数据显示一些加载.
import React from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';
class Testx extends React.Component {
constructor(props) {
super(props);
this.state = {
data:{}
};
}
componentDidMount(){
var self = this;
axios.get('http://localhost/index.php')
.then(function (response) {
self.setState({ data: response.data});
})
.catch(function (error) {
console.log(error);
});
}
render() {
const { data }= this.state;
if(data.firma) {
return (<div>
<input type="text" defaultValue={data.firma}/>
</div>);
}
return <div>loading...</div>;
}
}
ReactDOM.render(<Testx/>, document.getElementById('hello'));
发布于 2017-08-17 09:27:46
最初,数据状态是数组格式的。所以this.state.data.firma
不起作用。相反,将其设置为空对象{}
。
import React from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';
class Testx extends React.Component {
constructor(props) {
super(props);
this.state = {
data: {}
};
}
componentDidMount() {
var self = this;
axios.get('http://localhost/index.php')
.then(function (response) {
self.setState({ data: response.data});
})
.catch(function (error) {
console.log(error);
});
}
render() {
return <div>
<input type="text" defaultValue={this.state.data.firma}/>
</div>
}
}
ReactDOM.render(<Testx/>, document.getElementById('hello'));
发布于 2017-08-17 09:28:21
“代码样式”已经过时了。尝试使用绑定函数的箭头函数,例如setState
。或者在构造函数中绑定一次,比如this.myFunction = myFunction.bind(this)
,这样就可以访问this
了。我已经评论过,this.state.data
被声明为一个数组。要么将其更改为对象,要么通过特定的索引访问对象。
class Testx extends React.Component {
constructor(props) {
super(props);
this.state = {
data:{}
};
}
componentDidMount = () => { //Note the arrow function to bind this function
//Functions like componentDidMount are usually already bound
axios.get('http://localhost/index.php')
.then((response) => {
this.setState({ data: response.data});
})
.catch((error) => {
console.log(error);
});
}
render() {
return (
<div>
<input type="text" defaultValue={this.state.data.firma}/>
</div>
);
}
}
如果您的响应是数组而不是对象,那么尝试像这样访问firma
:this.state.data[index].firma
https://stackoverflow.com/questions/45741256
复制