简体   繁体   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>
  );
}

Adjusting the sliders changes the value in the array correctly.调整滑块会正确更改数组中的值。 (you can confirm through the console.log). (可以通过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?是因为 Flatlist 还是我需要触发重新渲染?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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