簡體   English   中英

React Native - 文本不隨數組值更新

[英]React Native - Text not updating with array value

import React, {useState} from 'react';
import { FlatList, Text, View} from 'react-native';
import {styles, styleBox} from './components/styles';
import Slider from '@react-native-community/slider';

export default function App() {
  const [values, setValues] = useState([
    {key: 'borderTopLeftRadius', display: 'Top Left', value: 0},
    {key: 'borderTopRightRadius', display: 'Top Right', value: 0},
    {key: 'borderTopStartRadius', display: 'Top Start', value: 0},
    {key: 'borderTopEndRadius', display: 'Top End', value: 0},
    {key: 'borderBottomLeftRadius', display: 'Bottom Left', value: 0},
    {key: 'borderBottomRightRadius', display: 'Bottom Right', value: 0},
    {key: 'borderBottomStartRadius', display: 'Bottom Start', value: 0},
    {key: 'borderBottomEndRadius', display: 'Bottom End', value: 0}
  ]);      

  const valueChangedHandler = (val, item) => {
    var index = values.findIndex(value => value.key == item.key);
    var newValues = values;
    newValues[index].value = val;
    setValues(newValues);
    console.log(values[index].value);
  }  

  return (
    <View style={styles.container}>      
      <View style={styleBox(values)}>        
      </View>      

      <FlatList
        data={values}
        renderItem={({item}) => (
          <View style={styles.Item}>
            <Text style={styles.Label}>{item.display}</Text>      
            <Slider 
              style={styles.slider}
              value={item.value} 
              onValueChange={value => valueChangedHandler(value, item)}
              minimumValue={0}
              maximumValue={100}
              step={1}
            />
            <Text>{item.value}</Text>
          </View>
        )}
      />
    </View>
  );
}

調整滑塊會正確更改數組中的值。 (可以通過console.log確認)。

但是滑塊后的文本不會改變,即使值本身發生了變化。

是因為 Flatlist 還是我需要觸發重新渲染?

試試這個方法,

 const valueChangedHandler = (val, item) => {
    var index = values.findIndex(value => value.key == item.key);
    var newValues = values;
    newValues[index].value = val;

    //spread operator will return new array with updated values
    setValues([...newValues]); 
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM