简体   繁体   中英

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>
  );
}

Adjusting the sliders changes the value in the array correctly. (you can confirm through the console.log).

But the text after the slider doesn't change, even though the value itself changed.

Is it because of the Flatlist or do i need to trigger a rerender?

Try this approach,

 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]); 
  }

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-2024 STACKOOM.COM