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

Categories

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

reactjs - Change text using hooks in react native

I have a very simple question. I am using hooks, and in the docs there is an example given to change the text using hooks. But there is place where I am not able to figure it out.

Below is my code:

import React, { useState } from 'react';
import { Text, View, TouchableOpacity } from 'react-native';

const HelloWorldApp = () => {

    const [textUpdate, setText] = useState('text1');
    const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]);

    return (
        <View style={{flex: 1, justifyContent: 'center', alignItems: 'center' }}>
                <Text>{textUpdate}</Text>
                <Text>{todos.text}</Text>
        </View>
    );
}

export default HelloWorldApp;

I can see text1 on the screen, But I cant see Learn hooks on the screen. What is wrong with <Text>{todos.text}</Text> ??

EDIT

So I changed <Text>{todos.text}</Text> to <Text>{todos[0].text}</Text>. Now I wanted to change the text on the click.

<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
    <Text>{textUpdate}</Text>
    <Text>{todos[0].text}</Text>
    <TouchableOpacity onPress={changeText} >
        <Text>Click me</Text>
    </TouchableOpacity>
</View>

and also added changeText in the component.

const changeText = () => {
    if (textUpdate === 'text1' || todos[0].text === 'Learn') {
        setText('text2');
        setTodos({ text: 'done' })
    } else if (textUpdate === 'text2' || todos[0].text === 'done') {
        setText('text1');
        setTodos({ text: 'Learn' })
    }
}

It gives an error undefined is not an object (evaluating 'todos[0].text')


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

1 Answer

0 votes
by (71.8m points)

UPDATED ISSUE

You have initialized state an array of object and reset it like object only

UPDATED SOLUTION

Try using as an array of an object like

const changeText = () => {
    if (textUpdate === 'text1' || todos[0].text === 'Learn') {
        setText('text2');
        setTodos([{ text: 'done' }]) // add like array
    } else if (textUpdate === 'text2' || todos[0].text === 'done') {
        setText('text1');
        setTodos([{ text: 'Learn' }])  // add like array
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
...