我需要你的帮助。我在更新页面上的数据时遇到问题。基本上我有一个主页,其中包含从登录中检索的“名字:...”、“姓氏:...”等数据。
登录完成后,每次启动应用程序时,您都会自动进入主页。 这样我就检索了主页页面上的信息。
问题是用户可以通过表单 (ModifyProfile) 修改此数据,并且一旦数据完成,它们就不会更新。 我怎样才能更新它们呢? 谢谢。
Homepage.js
class HomepageUtente extends Component {
constructor(props) {
super(props);
this.state = {
}
}
render() {
const FirstName = global.utente.data.Person.FirstName;
const LastName = global.utente.data.Person.LastName;
return (
<View style={style.container}>
<View style={style.page}>
<Icon name="user-circle" color="#64c7c0" size={70} onPress={() => Actions.yourprofile({ cf: Username } )} />
<Text
style={{ textAlign: 'center', fontSize: 20, }}>{"Welcome"}
</Text>
<Text style={{ textAlign: 'center', fontSize: 20, color: '#64c7c0', fontWeight: 'bold' }}>
{FirstName} {LastName}
</Text>
<Text style={{ color: '#64c7c0', paddingTop: 20 }} onPress={() => Actions.ModifyProfile({ cf: Username })} >Modify Profile</Text>}
</View>
</View>
)
}
}
修改配置文件
export default class ModificaProfilo extends Component {
constructor(props) {
super(props);
this.state = {};
}
findUtente(cf) {
//Search data cf in the db
//......
//......
.then(response => {
let utente = response.docs[0];
console.log("Utente: " + utente)
console.log("Sei qui 1")
utente.Person.FirstName = this.state.FirstName;
utente.Person.LastName = this.state.LastName;
global.utente.db.localdb().put(utente);
})
.catch(function(err) {
console.log(JSON.stringify(err));
})
}
render() {
return (
<View style={style.container}>
<View style={style.page}>
<KeyboardAwareScrollView>
<View style={style.inputContainer}>
<TextInput
style={style.inputs}
placeholder="Name"
placeholderTextColor="#64c7c0"
keyboardType="default"
underlineColorAndroid="grey"
onChangeText={FirstName =>
this.setState({ FirstName })
}
/>
</View>
<View style={style.inputContainer}>
<TextInput
style={style.inputs}
placeholder="Surname"
placeholderTextColor="#64c7c0"
keyboardType="default"
underlineColorAndroid="grey"
onChangeText={LastName =>
this.setState({ LastName })}
/>
</View>
<View style={style.footer}>
<TouchableOpacity
style={[style.button, style.buttonOK]}
onPress={() => this.findUtente(this.props.cf)}
>
<Text style={style.buttonTesto}>Modifica</Text>
</TouchableOpacity>
</View>
最佳答案
实际上,您可以这样做,但不应该这样做。我们先解决这个问题。
Homepage.js
中的组件,我们称之为A
;ModifyProfile
中的组件,我们称之为B
;
您需要对组件 A
的引用,然后调用A.forceUpdate()
。
这意味着您添加 global.A = this
在Homepage.js
;
添加global.A.forceUpdate()
在ModifyProfile
获得新数据后;
原因:React Component 仅当组件的 state 或 props 发生变化时才会重新渲染,这就是为什么你需要调用 forceUpdate
制作组件A
无条件地再次重新渲染。
如果您更改FirstName
通过global.utente.data.Person.FirstName = 'NewName'
,组件A
无法检测到更改事件。
顺便说一句,您应该使用像 redux
这样的状态容器来帮助你,而不是全局变量。您可以联系FirstName
作为你的 Prop 。
我推荐dvajs这很容易学习,你可以只关注数据和流程,大多数时候你不需要关心组件是否应该更新。
还有一个 dvajs
的启动器,您可以快速运行它,然后:
react-native-dva-starter
如果我误解了你的问题,那就算了。
关于javascript - 更新页面数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56861119/