Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
117 views
in Technique[技术] by (71.8m points)

reactjs - How can I call a function when the screen is being navigated by other screen with passing variable

I have issue while handling React Native Lifecycle whereby I have a function call "getData()" should be load before render() method is being triggered. I have tested to applied "ComponentDidMount" but it does not work because the component does not being render. As I know, the sequence of the RN lifecycle will be :

  1. constructor()
  2. static getDerivedStateFromProps()
  3. render()
  4. componentDidMount()

I was thinking am I able to put the function inside the constructor but I get a warning indication and the function is not loaded once the screen is being navigated or startup. Does anyone know how can I preload the function before the render occurs?

Below are my current code:

import React, { Component } from "react";
import {
    Modal,
    StyleSheet,
    ScrollView,
    View,
    TouchableOpacity,
    KeyboardAvoidingView,
} from 'react-native';
import CustomHeader from './CustomHeader';
import { NavigationActions } from 'react-navigation';
import { StackActions } from 'react-navigation-stack';
import { Col, Row, Grid } from 'react-native-easy-grid';
import { Form, Label, Body, Item, Text, Right, Left, Footer, Icon, List, Container, Spinner, ListItem, Content, CheckBox, Button, H3, H2, H1 } from 'native-base';
import Moment from 'moment';
import axios from 'axios';
import { ApiURL } from "../constants/master";

class TransactionDetailScreen extends Component {
    constructor(props) {
        super(props);
        this.state = {
            restaurantName: '',
            transactionDetails: [],
            transactionId: '',
            total: 0.00,
            mode: ''
        }
        this.loadTransactionDetails();
    }

    loadTransactionDetails() {
        
        if (this.props.navigation.state.params){
            this.setState({transactionId:this.props.navigation.state.params.transactionId});
            const id = this.props.navigation.state.params.transactionId;
        console.log(`id:${id}`);
        console.log(`${ApiURL}/transaction/${id}`);
        axios.get(`${ApiURL}/transaction/${id}`)
            .then(resp => {
                if (resp.status === 200){
                    const res = resp.data.info;
                    this.setState({transactionDetails:res,mode:res.mode});
                }
                else{
                    alert(resp.data.error);
                }
            }).catch((error) => {
                alert("err:" + error.message)
            });
        }
    }

    componentDidMount() {
        console.log(this.props.navigation.state.params);
        this.loadTransactionDetails();
           
    }

    static navigationOptions = () => ({
        headerShown: false
    })

    render() {
        return (
            <Container>
                <CustomHeader isHome={false} navigation={this.props.navigation} backScene="Transaction" title="Transaction Detail" />
                <Content style={{ backgroundColor: "#f8f9fa" }}>
                    <ListItem itemDivider>
                        <Text>{this.state.mode}</Text>
                    </ListItem>
                    <Grid style={{ backgroundColor: "white", paddingVertical: 15, paddingHorizontal: 15 }}>
                        <Row>
                            <Text style={styles.lgText}>{this.state.transactionDetails.localMsg}</Text>
                        </Row>
                        <Row>
                            <Col>
                                <View alignItems="flex-end">
                                    <Text style={{ fontSize: 20 }}>
                                        RM
                                            <Text style={{ fontSize: 35 }}>
                                            {parseFloat(this.state.transactionDetails.amount).toFixed(2)}
                                        </Text>
                                    </Text>

                                </View>
                            </Col>
                        </Row>
                    </Grid>
                    <Grid style={{ backgroundColor: "white", paddingHorizontal: 15, marginTop: 15 }}>
                        <Row style={{ paddingTop: 10 }} >
                            <Col size={50}>
                                <Text style={styles.colHeading}>{this.state.mode === "Payment" ? "Merchant" : "Payment method"}</Text>
                            </Col>
                            <Col alignItems="flex-end" size={50}>
                                <Text style={styles.colBody} alignSelf="flex-end">{this.state.mode === "Payment" ? this.state.transactionDetails.merchant : this.state.transactionDetails.paymentMethod}</Text>
                            </Col>
                        </Row>
                        <Row style={{ paddingTop: 10 }} >
                            <Col size={50}>
                                <Text style={styles.colHeading}>Date</Text>
                            </Col>
                            <Col alignItems="flex-end" size={50}>
                                <Text style={styles.colBody} alignSelf="flex-end">{this.state.transactionDetails.createdAt && Moment(this.state.transactionDetails.createdAt).format('L LT')}</Text>
                            </Col>
                        </Row>
                        {
                            this.state.mode === "Payment" && (
                            <Row style={{ paddingTop: 10 }} >
                            <Col size={50}>
                                <Text style={styles.colHeading}>Order ID</Text>
                            </Col>
                            <Col alignItems="flex-end" size={50}>
                                <Text style={styles.colBody} alignSelf="flex-end">{this.state.transactionDetails.orderId}</Text>
                            </Col>
                        </Row>)
                        }
                        <Row style={{ paddingVertical: 10 }} >
                            <Col size={50}>
                                <Text style={styles.colHeading}>Transaction ID</Text>
                            </Col>
                            <Col alignItems="flex-end" size={50}>
                                <Text style={styles.colBody} alignSelf="flex-end">{this.props.navigation.state.params ? this.props.navigation.state.params.transactionId : null}</Text>
                            </Col>
                        </Row>
                    </Grid>
                    {
                        this.state.mode === "Payment" && (
                            <>
                            <ListItem itemDivider style={{ marginTop: 20 }}>
                        <Text>Payment Item</Text>
                    </ListItem>
                    <List style={{ backgroundColor: "white" }}>
                        {
                            this.state.transactionDetails.items.map((item,i) => {
                                return (
                                    <ListItem key={i}>
                                        <Body>
                                            <Grid>
                                                <Row style={{ marginBottom: 10 }}>
                                                    <Col>
                                                        <Text><H3>{item.name}</H3></Text>
                                                    </Col>
                                                </Row>
                                                <Row style={{ marginBottom: 5 }}>
                                                    <Col><Text style={{ alignSelf: 'flex-end' }}>RM {parseFloat(item.paidAmount).toFixed(2)}</Text></Col>
                                                </Row>
                                            </Grid>
                                        </Body>
                                    </ListItem>
                                )
                            })
                        }
                    </List>
                            </>
                        )
                    }
                </Content>
            </Container>
        );
    }
};

const styles = StyleSheet.create({
    container: {
        flex: 1
    },
    lgText: {
        fontSize: 18
    },
    colHeading: {
        fontSize: 16,
        fontWeight: 'bold'
    },
    colBody: {
        fontSize: 16
    }
});

export default TransactionDetailScreen;
question from:https://stackoverflow.com/questions/65839049/how-can-i-call-a-function-when-the-screen-is-being-navigated-by-other-screen-wit

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

That is not possible in your case, as it is an API call.

However if you call an API in constructor, it will be gone in background and your current component will execute render()

So the best way to call it in componentDidMount() and than set your state variable accordingly.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...