简体   繁体   English

如何将数据从类传递到 React Native 数组、firebase、堆栈导航器 v5 中的函数

[英]How to pass data from Class to function in React Native array, firebase, stack navigator v5

Hay I am struggling on how to pass data that's in a class, to another react native component.嘿,我正在努力研究如何将类中的数据传递给另一个反应本机组件。 I am able to display data on the same screen, however I want to have the user input some text and have it display on another screen.我能够在同一屏幕上显示数据,但是我想让用户输入一些文本并将其显示在另一个屏幕上。

1) Initial Screen: User presses button to navigate to text inputs, and will navigate back to this screen to view the list. 1) 初始屏幕:用户按下按钮导航到文本输入,然后导航回此屏幕以查看列表。 Note : If I add the list here I get an error " undefined is not an object ".注意:如果我在此处添加列表,则会收到错误消息“未定义不是对象”。 Because I was not able to figure out how to PASS THE LISTARRAY variable to that screen.因为我无法弄清楚如何将 LISTARRAY 变量传递到该屏幕。

export const GoalsScreen = ({ navigation }) => {

    return (
        <SafeAreaView style={styles.container}>
            <Header>
                {/* header title */}
                <Text style={styles.goalText}> Expand your life</Text>

                {/* add goal button goto stack */}
                <TouchableOpacity onPress={() => navigation.navigate("AddGoal")} >
                    <Text style={styles.addBtn}> + </Text>
                </TouchableOpacity>
            </Header>

            {/* Error here, need to get data from other screen */}
            <FlatList
                data={this.state.listArray}
                renderItem={({ item, index }) => {
                    return (
                        <View>
                            <Text style={{ fontSize: 30 }}>{item.fireListGoal} </Text>
                            <Text style={{ fontSize: 20 }}>{item.fireListCat}</Text>
                            <Text style={{ fontSize: 15 }}> {item.fireListWhy}</Text>
                        </View>
                    );
                }}
            >
            </FlatList>

        </SafeAreaView>
    );
}

2) List Screen: If I put the flatList here everything works, but I need to PASS THE DATA thats inputted here in the firebase real-time database and display it on the other screen shown above. 2) 列表屏幕:如果我将 flatList 放在这里,一切正常,但我需要将此处输入的数据传递到 firebase 实时数据库中,并将其显示在上面显示的另一个屏幕上。



export class AddGoalList extends React.Component {

    // state and defult values
    constructor(props) {
        super(props)

        // set inital values
        this.state = {
            listArray: [],
            goal: '',
            category: 'Pick One',
            why: '',
        }
    }

    //triggers rerendering, put values in a JSON array
    componentDidMount() {
        goalsRef.on('value', (childSnapshot) => {
            const listArray = [];
            childSnapshot.forEach((doc) => {
                listArray.push({
                    key: doc.key,
                    fireListGoal: doc.toJSON().fireListGoal,
                    fireListCat: doc.toJSON().fireListCat,
                    fireListWhy: doc.toJSON().fireListWhy
                });
                this.setState({
                    listArray: listArray.sort((a, b) => {
                        return (
                            a.fireListGoal < b.fireListGoal,
                            a.fireListCat < b.fireListCat,
                            a.fireListWhy < b.fireListWhy
                        );

                    }),
                });
            });
        });
    }



    // when button pressed... 
    onGoal = ({ }) => {
        // if form empty alert user
        if (this.state.goal.trim() && this.state.why.trim() === '') {
            alert("Please fill form.");
            return;
        }
        if (this.state.category.valueOf() === 'Pick One') {
            alert("Fill in all inputs.");
            return;
        }
        // otherwise push data to firebase
        goalsRef.push({
            fireListGoal: this.state.goal,
            fireListCat: this.state.category,
            fireListWhy: this.state.why
        });
    }

    render() {

        return (
            // KeyboardAvoidingView ==> prevent keyboard from overlapping
            <KeyboardAvoidingView style={styles.container}>
                <SafeAreaView>
                    <Text>Sparks your life!</Text>

                    {/* Goal title */}
                    <Text>What is your goal</Text>

                    <TextInput
                        placeholder="Enter your goal"
                        keyboardType='default'
                        onChangeText={
                            (text) => {
                                this.setState({ goal: text });
                            }
                        }
                        value={this.state.goal}
                    />

                    {/* pick selected cetegory */}
                    <Text>Pick a Category</Text>
                    {/* picker component */}
                    <Picker
                        selectedValue={this.state.category}
                        onValueChange={(itemValue) => this.setState({ category: itemValue })}
                    >
                        <Picker.Item label="Pick One" value="Pick One" />
                        <Picker.Item label="Fitness" value="Fitness" />
                        <Picker.Item label="Health" value="Health" />
                        <Picker.Item label="Travel" value="Travel" />
                        <Picker.Item label="Wealth" value="Wealth" />
                        <Picker.Item label="Creativity" value="Creativity" />
                        <Picker.Item label="Skills" value="Skills" />

                    </Picker>

                    <Text>Why did you pick this goal?</Text>

                    <TextInput
                        placeholder="Enter your why"
                        keyboardType='default'
                        onChangeText={
                            (text) => {
                                this.setState({ why: text });
                            }
                        }
                        value={this.state.why}
                    />

                    {/* nav back to My Goal list */}
                    <Button title="add goal" onPress={this.onGoal.bind(this)} />
                </SafeAreaView>

                {/* remove list here and add to other GoalsScreen */}
                <FlatList
                    data={this.state.listArray}
                    renderItem={({ item, index }) => {
                        return (
                            <View> 
                                <Text style={{fontSize: 30}}>{item.fireListGoal} </Text>
                                <Text style={{fontSize: 20}}>{item.fireListCat}</Text>
                                <Text style={{fontSize: 15}}> {item.fireListWhy}</Text>
                            </View>
                        );
                    }}
                >
                </FlatList> 



            </KeyboardAvoidingView>

        );
    }
}

I have tried to useState and pass data as a param but got errors, in able to use the variable navigation in a class..?我尝试过 useState 并将数据作为参数传递但出现错误,无法在类中使用变量导航..? Also tried to put it in a separate function and that did now work ether.还尝试将它放在一个单独的函数中,现在确实可以工作。 I'll add my code bellow so you can take a look.我将在下面添加我的代码,以便您可以查看。 Any suggestions and or references to any helpful docs would really be appreciated.对任何有用文档的任何建议和/或参考将不胜感激。

Would really appreciate some help, been trying to resolve this for the past few days with no luck.真的很感激一些帮助,过去几天一直在努力解决这个问题,但没有运气。 Many thanks!非常感谢!

If i understand the flow correctly, what you want is the following: Initially, you have a first screen with a list of items (GoalsScreen).如果我正确理解流程,您想要的是以下内容:最初,您有一个带有项目列表的第一个屏幕(GoalsScreen)。 From there the user can open a new screen, where he can add items (AddGoalScreen).用户可以从那里打开一个新屏幕,他可以在其中添加项目 (AddGoalScreen)。 So, when the user goes back, you want him to see the updated list.因此,当用户返回时,您希望他看到更新后的列表。

First of all, in the above code, the GoalsSrceen has not defined any state listArray, so that's why you get undefined error.首先,在上面的代码中,GoalsSrceen 没有定义任何状态 listArray,所以这就是你得到 undefined 错误的原因。 You need to declare it just like you did in AddGoalScreen.您需要像在 AddGoalScreen 中一样声明它。 Also, as i can see, the AddGoalScreen will no longer display this listArray, so you can simply move the goalsRef.on('value', ... subscription in the GoalsScreen. Doing so, each time you push to the firebase through AddGoalScreen, the on('value') subscription will be triggered inside GoalsScreen, and the GoalsScreen will rerender, keeping its state available. So you have your problem fixed另外,正如我所看到的,AddGoalScreen 将不再显示这个 listArray,所以你可以简单地移动目标goalsRef.on('value', ...在目标屏幕中订阅。这样做,每次你通过 AddGoalScreen 推送到 firebase 时, on('value')订阅将在目标屏幕内触发,目标屏幕将重新渲染,保持其状态可用。所以你的问题得到了解决

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 尝试在反应本机堆栈导航器 v5 中访问 route.params - Trying to access route.params in react native stack navigator v5 如何在反应原生导航 v5 中将 go 返回到另一个堆栈? - How to go back to another stack in react native navigation v5? React Navigation V5 在 Stack Navigator 中隐藏底部标签栏 - React Navigation V5 hide Bottom tab bar in Stack Navigator 如何在 react native navigation v5 中将数据传递回上一个屏幕? - How to pass data back to previous screen in react native navigation v5? React Native中的Stack Navigator - Stack Navigator in react native React 本机堆栈导航器:如何传递参数?? 我不能传递参数 - React native stack navigator : how to pass params?? i can't pass params 如何将 function 和组件 class 中的数据传递给 React Native 中的无状态 class? - How to pass function and data from component class to stateless class in React Native? 如何在 react-native 中结合使用 Drawer Navigator 和 Stack Navigator? - How to use Drawer Navigator & Stack Navigator combined in react-native? 在React Native中如何在重置导航堆栈的同时从子Stack Navigator导航回父项 - How to navigate from a child Stack Navigator back to parent while resetting navigation stack at the same time, in React Native 从抽屉导航器到标签导航器反应本机传递参数 - React Native Pass Param From Drawer Navigator to Tab Navigator
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM