简体   繁体   中英

react-native undefined variable

I got a problem with my variable on react-native. When I display my variable with console.log() everything is good I got its content. But when I use it with map my variable is undefined. Here my code.

const ServiceAction = (props) => {
    const { services } = props;
    console.log("Services:", services)
    return services.map((service, index) => {return <Text key={index}>{service.name}</Text>})
}

So here services is undefined when I use it with map but not when I display it.

I call my function just before.

 const Dashboard: () => React$Node = (props) => {
        // const [state, dispatch] = React.useReducer(userReducer, props.navigation.getParam("user"));
        // const ip = props.navigation.getParam("ip");

        const ip = "192.168.1.37";
        const [state, dispatch] = React.useReducer(userReducer, initialStateUser);

        const [services, setServices] = React.useState([]);
        const [serviceAction, setServiceAction] = React.useState("Default");

        React.useEffect(() => {
            fetch(`http://${ip}:8080/about.json`)
                .then((response) => {return response.json()})
                .then((data) => setServices(data.server.services))
                .catch((err) => console.log(err))
        },[])


        return (
            <LinearGradient start={{x: 0, y: 0}} end={{x: 1, y: 1}} colors={['rgba(58,115,215,1)', 'rgba(44,120,215,1)', 'rgba(68,116,213,1)', 'rgba(47,105,191,1)', 'rgba(131,75,191,1)', 'rgba(198,98,237,1)']} style={styles.linearGradient}>
                <Image style={{width: 400, height: 50}} source={require('../assets/logo.png')}/>
                <ServiceAction services={services} />
            </LinearGradient>
        )
    }

If someone has an idea ...

EDIT:

Service is a JSON format

Services = [{
  name: 'toto'
 }, {
  name: 'titi'
 }
]

try like this:

const ServiceAction = (props) => {
    const { services } = props;
    let testArray = []
    console.log("Services:", services)
    services.map((service, index) => {testArray.push(<Text key={index}>{service.name}</Text>)})
    return testArray
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM