我试图在迭代值后将 data.rate 附加到 this.state.test 中,问题是数据没有显示在测试中
export default class LiveApiData extends Component {
constructor() {
super();
this.state = { ndata: [], test: [] };
}
componentDidMount() {
fetch('')
.then((response) => response.json())
.then((data) => this.setState({ ndata: data }));
}
render() {
let x = this.state.ndata.map((data) => this.setState({ test: data.rate }));
return (
<View>
<Text> {x} </Text>
</View>
);
}
}
console.log 之后我的 api 示例
0:{timestamp:"2018-04-14T00:00:00Z",rate:"7999.09816231845214650049179249741253"}
►1:{timestamp:"2018-04-15T00:00:00Z",rate:"8357.6586830697213301743207363910892"}
►2:{timestamp:"2018-04-16T00:00:00Z",rate:"8046.07792934854261706414967686716349"}
答案 0 :(得分:0)
如果您的测试只是您状态的派生值,那么您就不是它的状态。
export default class LiveApiData extends Component {
constructor() {
super();
this.state = { ndata: [] };
}
componentDidMount() {
fetch('')
.then((response) => response.json())
.then((data) => this.setState({ ndata: data }));
}
render() {
let x = this.state.ndata.map((data) => { test: data.rate });
return (
<View>
<Text> {x} </Text>
</View>
);
}
}
这里不是 x
是 [],所以可能需要将其映射如下
{x.map(({test}, index) => <Text key={index}> {test} </Text>)}
答案 1 :(得分:0)
假设data
调用中收到的then
是一个对象数组,每个对象包含rate
componentDidMount() {
fetch('')
.then((response) => response.json())
.then((data) => {
const ndata = data
const test = data.map((element)=>element.rate)
this.setState({ndata:ndata, test:test})
});
}