我是React-Native
及其states
的新手,这里我遇到了一个问题(使用虚拟数据,但我的问题是相同的),我想要实现的就是获取最新的{{1} }从JSONARRAY
获取,基于我单击按钮一时的按钮单击,它应该仅返回state
,其他按钮也应采用类似的方法,并且对您有所帮助
我已附上
答案 0 :(得分:0)
编辑:根据您的评论,听起来您的问题是您不想多次添加相同的值。在这种情况下,应对此进行修复:
export default class App extends React.Component {
state= {
selectedPosition:0,
}
render() {
const value = data[this.state.selectedPosition].joinedUsers
value[0]["key"] = "mutatedFruit"
return (
<View style={styles.container}>
<Button title='ONE'
onPress={()=>this.setState({selectedPosition:0})}></Button>
<Button title='TWO'
onPress={()=>this.setState({selectedPosition:1})}></Button>
<Button title='THREE'
onPress={()=>this.setState({selectedPosition:2})}></Button>
<Button title='FOUR'
onPress={()=>this.setState({selectedPosition:3})}></Button>
<Text>{JSON.stringify(value)}</Text>
</View>
);
}
}
答案 1 :(得分:0)
希望下面的代码有帮助,
import * as React from 'react';
import { Text, View,Button, StyleSheet } from 'react-native';
import Constants from 'expo-constants';
// You can import from local files
import AssetExample from './components/AssetExample';
const data = [
{"joinedUsers":[{"one":"oneKey"}],"key":"mango"}
,{"joinedUsers":[{"two":"twoKey"}],"key":"apple"}
,{"joinedUsers":[{"three":"threeKey"}],"key":"banana"}
,{"joinedUsers":[{"four":"fourKey"}],"key":"kiwi"}];
// or any pure javascript modules available in npm
import { Card } from 'react-native-paper';
export default class App extends React.Component {
constructor(props){
super(props);
this.state={
selectedPosition:0,
valueArr : []
}
}
componentDidMount(){
let newVal = [];
newVal.push(data[0].joinedUsers[0])
newVal.push({"key":"mutatedFruit"})
this.setState({valueArr:newVal})
}
setValues = (position) => {
let newVal = [];
newVal.push(data[position].joinedUsers[0])
newVal.push({"key":"mutatedFruit"})
this.setState({valueArr:newVal})
}
render() {
const value = data[this.state.selectedPosition].joinedUsers
value.push({"key":"mutatedFruit"})
return (
<View style={styles.container}>
<Button title='ONE'
onPress={()=>this.setValues(0)}></Button>
<Button title='TWO'
onPress={()=>this.setValues(1)}></Button>
<Button title='THREE'
onPress={()=>this.setValues(2)}></Button>
<Button title='FOUR'
onPress={()=>this.setValues(3)}></Button>
<Text>{JSON.stringify(this.state.valueArr)}</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
padding: 8,
flexDirection:'column'
},
paragraph: {
margin: 24,
fontSize: 18,
fontWeight: 'bold',
textAlign: 'center',
},
});