React Native 在当前更改时不重新渲染 arr ref

react native dont re render the arr ref when current changes

提问人:Benjamin Hanonove 提问时间:9/18/2023 更新时间:9/18/2023 访问量:15

问:

我尝试从文本输入创建动态下拉列表,该下拉列表将保存关闭字符串的值, 我使用 ref 来保存文本输入值和我从 API 读取返回的 arr。 在控制台中,我每次都看到值发生变化,但是当我在下拉组件中传递 arr ref 时,组件本身不会更改。

开始屏幕 :

`import React, { useRef } from 'react';
import styled ,{css} from 'styled-components/native';
import { Container, screenWidth } from '../utils/shared';
import { StackNavigationProp } from '@react-navigation/stack';
import { StackParamList } from '../navigation/StackNavigation';
import { useNavigation } from '@react-navigation/native';
import { getCityByName } from '../utils/cityApi';
import mapPng from "../assets/map.png";

//Components
import BackArrowButton from '../components/Buttons/BackArrowButton';
import Search from '../components/Inputs/Search';
import RegularText from '../components/Text/RegularText';
import TextButton from '../components/Buttons/TextButton';
import RegularButton from '../components/Buttons/RegularButton';
import Dropdown from '../components/Sliders/Dropdown';

const StartScreen: React.FC = () => {

    //Ref to save and update the value of the text input
    const nameRef = useRef<string>("");
    const updateNameRef = (name: string)=>{
      nameRef.current = name;
      fetchCities();
    };

    
    //Ref to save and update the values of the dropdown arr
    const arrRef = useRef<string[]>([]);
    const addToArr = (value: string) => {
      arrRef.current = [value, ...arrRef.current];
    };
    

    //Create of navigation
    type stackProps = StackNavigationProp<StackParamList ,"Start">;
    const navigation = useNavigation<stackProps>();

    //Function that handles 
    const goBack = () =>{
      navigation.navigate("Welcome");
    };

    //Function to skip the choose of the city
    const skipPress = () =>{
      navigation.navigate("Home")
    };

    //Image for start screen
    const StyledImage = styled.Image`
      width: 60%;
      height: 200px;
      object-fit:cover;
    `;

    //View to hold the elements center
    const StyledView = styled.View`
    justify-content:space-between;
    align-items: center;
    height: 400px;
    display: flex;
    width: ${screenWidth}px;
    `;

    //Css props for margin-top between the elements inside the view
    const customSpace = css`
      margin-top: 21px;
    `;


    //Function that reads api call and put it inside arr ref
    const fetchCities = async () => {
      arrRef.current = [];
      if (nameRef.current !== "") {
        const arr = await getCityByName(nameRef.current, 0, 5);
        if (arr) {
          arr.forEach((element: string) => {
            addToArr(element);
          });
        };
      }else{
        arrRef.current = [];
      };

      console.log(arrRef);
    };

  return (
    <Container>
      <BackArrowButton onPress={goBack}/>

    <StyledView>
      <StyledImage source={mapPng} />
      <RegularText str='Please enter your location' customCss={customSpace}/>
      <Search placeHolder='City...' updateNameRef={updateNameRef}/>

      <Dropdown arr={arrRef} key={arrRef.current.length}/>
      
      <RegularButton ButtonText='Enter' onPress={skipPress} customCss={customSpace}/>
      <TextButton str='skip' onPress={skipPress} size={17}  customCss={customSpace}/>
    </StyledView>

    </Container>
  );
}

export default StartScreen;`

这是下拉组件:

import React from 'react';
import styled from 'styled-components/native';
import { colorPalette } from '../../utils/colors';
import { screenWidth } from '../../utils/shared';

//Components
import NameCard from '../Cards/NameCard';
import { FlatList } from 'react-native';

interface DropdownProps {
    arr: React.MutableRefObject<string[]>;
}

const StyledView = styled.View`
    max-height: 90px;
    min-height: 0px;
    width: ${screenWidth*0.7}px;
    background: ${colorPalette.white};
    border-radius: 0px 0px 7px 7px;
    position: relative;
    padding-top: 7px;
`;

const BorderInside = styled.View`
    position: absolute;
    top: 1px;
    left: 2.5%;
    width: 95%;
    height: calc(100% - 0.5px);
    border: 0.2px solid grey;
`;


const Dropdown: React.FC<DropdownProps> = (props) => {
    return (
    <StyledView>
        <BorderInside />
        
        <FlatList
        data={props.arr.current}
        keyExtractor={(item) => item}
        renderItem={({ item }) => (
            <NameCard key={item} str={item} />
            )}
        />
    </StyledView>
    );
}

export default Dropdown;

我尝试将值传递到每次按键的下拉列表中

react-native react-hooks 回调 渲染 引用

评论

0赞 Kelsey 9/18/2023
您是否尝试过使用 componentDidUpdate 钩子?knowledgehut.com/blog/web-development/react-componentdidupdate
1赞 user18309290 9/19/2023
这回答了你的问题吗?React useRef 不更新和渲染新值

答: 暂无答案