在React Native中从其他组件更新道具 [英] Update props from other component in react native

查看:51
本文介绍了在React Native中从其他组件更新道具的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Main类,向用户显示一个数组,然后在详细页面中,用户可以使用react navigation参数编辑我要传递的每个元素。我想在detail类中编辑数组,并使用异步存储将其保存。

I have a Main class which I show an array to user, then in detail page user can edit each element which I'm passing using react navigation parameter. I want to edit my array in the detail class and save it using async storage.

//Main.jsimport React from 'react';
import {
    StyleSheet ,
     Text,
     View, 
     TextInput,
     ScrollView,
     TouchableOpacity,
     KeyboardAvoidingView,
     AsyncStorage
    } from 'react-native'
import Note from './Note'
import detail from './Details'
import { createStackNavigator, createAppContainer } from "react-navigation";


export default class Main extends React.Component {

  static navigationOptions = {
    title: 'To do list',
    headerStyle: {
      backgroundColor: '#f4511e',
    },
  };

  constructor(props){
    super(props);
    this.state = {
      noteArray: [],
      noteText: '',
      dueDate: ''
    };
  }

  async saveUserTasks(value) {
    try {
      await AsyncStorage.setItem('@MySuperStore:userTask',JSON.stringify(value));
    } catch (error) {
      console.log("Error saving data" + error);
    }
  }
   getUserTasks = async() =>{
    try {
      const value = await AsyncStorage.getItem('@MySuperStore:userTask');
      if (value !== null){
        this.setState({ noteArray: JSON.parse(value)});
      }
    } catch (error) {
      console.log("Error retrieving data" + error);
    }
  }

render() {
  this.getUserTasks()
    let notes = this.state.noteArray.map((val,key) => {
      return <Note key={key} keyval={key} val={val}
      deleteMethod={ () => this.deleteNote(key)}
      goToDetailPage= {() => this.goToNoteDetail(key)}
       />
    });
    const { navigation } = this.props;
    return(
      <KeyboardAvoidingView behavior='padding' style={styles.keyboard}>
        <View style={styles.container}>
            <ScrollView style={styles.scrollContainer}>
                {notes}
            </ScrollView>
            <View style={styles.footer}>
                <TextInput
                onChangeText={(noteText) => this.setState({noteText})}
                style={styles.textInput}
                placeholder='What is your next Task?'
                placeholderTextColor='white'
                underlineColorAndroid = 'transparent'
                >
                </TextInput>
            </View>
            <TouchableOpacity onPress={this.addNote.bind(this)} style={styles.addButton}>
                <Text style={styles.addButtonText}> + </Text>
            </TouchableOpacity>
        </View>
   </KeyboardAvoidingView>
      );
    }
    addNote(){
      if (this.state.noteText){
        var d = new Date();
        this.state.noteArray.push({ 
        'creationDate': d.getFullYear() + "/" + (d.getMonth()+1) + "/" + d.getDay(), 'taskName': this.state.noteText,'dueDate':'YYYY/MM/DD'
        });
        this.setState({noteArray:this.state.noteArray})
        this.setState({noteText: ''});
        this.saveUserTasks(this.state.noteArray) 
      }
    }
    deleteNote(key){
      this.state.noteArray.splice(key,1);
      this.setState({noteArray: this.state.noteArray})
      this.saveUserTasks(this.state.noteArray)       
    }
    goToNoteDetail=(key)=>{   
      this.props.navigation.navigate('DetailsScreen', {
        selectedTask: this.state.noteArray[key],
      });
    }     
}

详细视图中,我有这种方法类似于在主类中添加注释:

in detail view I have this method which is similar to add note in main class:

export default class Details extends React.Component {
  render() {
    const { navigation } = this.props;
    const selectedTask = navigation.getParam('selectedTask', 'task');
    return(
     <View key={this.props.keyval} style={styles.container}>
      <TouchableOpacity onPress={this.saveEdit.bind(this)} style={styles.saveButton}>
                <Text style={styles.saveButtonText}> save </Text>
      </TouchableOpacity>
    </View>
    );
  }
  saveEdit(){

    let selectedItem = { 'creationDate': selectedTask['creationDate'], 
    'taskName': selectedTask['taskName'],
    'dueDate': this.state.dueData}


this.props.navigation.state.params.saveEdit(selectedItem)
      }
    }

如何在任何组件中更改道具?

How can I change my props in any component?

推荐答案

首先,您不应该在render方法中调用this.getUserTasks(),因为该函数具有this.setState不好,并且可能以无休止的循环结束猜测或至少影响较差的性能。您可以改为在componentDidMount中调用它:

First of all you shouldn't call this.getUserTasks() in the render method because the function has this.setState which is bad and could end in a endless loop I guess or at least effect in worse performance. You could instead call it in componentDidMount:

componentDidMount = () => {
    this.getUserTasks();
}

或者在构造函数中已经调用,但我更喜欢第一种选择:

Or alternatively call already in constructor but I prefer the first option:

constructor(props){
  super(props);
  this.state = {
    noteArray: [],
    noteText: '',
    dueDate: ''
  };

  this.getUserTasks()
}

this.props .noteArray.push({..可能是未定义的,因为您没有将它传递到任何地方。(您的代码段中没有看到任何引用)。我想我会在Main.js组件中实现saveEdit函数,并且只需将其传递到导航路径,并通过访问导航状态props调用Details组件中的函数:

this.props.noteArray.push({.. is probably undefined because you aren't passing it down any where. (Didn't see any reference in your snippet). I guess I would implement the saveEdit function in the Main.js component and simply pass it down to the navigation route and call the function in Details component by accessing the navigation state props:

更新

  goToNoteDetail=(key)=>{   
    this.props.navigation.navigate('DetailsScreen', {
      // selectedTask: this.state.noteArray[key],
      selectedItem: key,
      saveEdit: this.saveEdit
    });
  }     

  saveEdit(selectedItem){
    const selectedTask = this.state.noteArray[selectedItem]
    this.state.noteArray.push({ 
      'creationDate': selectedTask['creationDate'], 
      'taskName': selectedTask['taskName'],
      'dueDate': this.state.dueData
    });
    this.setState({noteArray:this.state.noteArray})
    this.setState({dueData: 'YYYY/MM/DD'});
    this.saveUserTasks(this.state.noteArray) 
  }

在Details组件中调用saveEdit:

And then call saveEdit in Details Component:

saveSelectedItem = () => {
  const { navigation } = this.props.navigation;
  const {selectedItem, saveEdit} = navigation.state && navigation.state.params;
  saveEdit(selectedItem)
}

这篇关于在React Native中从其他组件更新道具的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆