如何在类组件React native中更改useEffect?

问题描述 投票:0回答:1

我想将我的代码从函数重写到类,但是我被useEffect函数卡住了。

我有一个在添加新元素后会更新的数组,但是函数countTotal在更新后开始工作。所以,1)打开App myArray有两个对象,总和= 0(但应为300)2)将总和为100的新对象添加到myArray三个对象中,总和= 300(应为400)

export default class Home extends Component {
    constructor(){
        super();
        this.state = {
            total:0,
            expenses:[
                { key: '1', sum: '100',  date: '12 April 2020' },
                { key: '2', sum: '200', date: '17 April 2020' },
            ],
        }
        this.submitHandler = this.submitHandler.bind(this);
        this.countTotal = this.countTotal.bind(this);
    }

    countTotal(){
        const totalSum = this.state.expenses.reduce((prev,next) => prev + Number(next.sum),0);
        this.setState({total: totalSum})
    }

    submitHandler (sum, date) {
        const key = Math.random().toString();
        const obj = {'key':key, 'sum':sum, 'date':date};

        this.setState(prevState => ({ 
                expenses: [obj, ...prevState.expenses]}))
        countTotal()  
    };  
    render(){
        return (
            <DismissKeyboard>
              <View style={styles.container}>

                <View style={styles.content}>
                  <TouchableOpacity onPress={this.showList}>
                    <Costs costs={this.state.total}  />
                  </TouchableOpacity>
                </View>


                <View style={styles.list}>
                  <FlatList
                    data={this.state.expenses}
                    renderItem={({ item }) => (
                      <ListCosts item={item} pressHandler={this.pressHandler} />
                    )}
                  />
                </View>

              </DismissKeyboard>

          );
        }
    }

因此它可以正常使用

useEffect= (()=> {
    const totalSum = expenses.reduce((prev,next) => prev + Number(next.sum),0);
    setTotal(totalSum)
    console.log(totalSum)
    } [expenses]);

我试图添加componentDidMount和componentDidUpdate,但一无所获。有什么建议吗?

reactjs react-native components
1个回答
0
投票

您发布的代码似乎工作正常。我创建了codeandbox网址https://codesandbox.io/s/affectionate-shaw-toe9p

仅上面的代码在功能组件和类组件之间存在差异

这里useEffect会在每次费用更改时被调用,但是componentDidMount在组件安装后将仅被调用一次。因此,我们必须创建一个函数,并在每次费用更新时调用该函数

setState(updater, [callback])

setState

因此,在调用setState时,我们可以将回调函数传递给setState并更新总值

© www.soinside.com 2019 - 2024. All rights reserved.