gpt4 book ai didi

javascript - React defaultValue 不工作 axios 传递动态数据

转载 作者:太空宇宙 更新时间:2023-11-04 02:01:42 25 4
gpt4 key购买 nike

你好,我是 React 新手,我正在尝试使用 React,但有一点我不明白。

首先,使用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'));

最佳答案

您需要等待数据到来并显示正在加载的内容。

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'));

关于javascript - React defaultValue 不工作 axios 传递动态数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45741256/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com