javascript - 如何调用使用状态(由另一个函数设置)并更新状态的函数

标签 javascript reactjs

我有两个函数,一个函数从 api 获取数据并根据该数据更新状态,另一个函数迭代状态中的数据并使用新数据更新状态。

我的问题是我无法更新第二个函数中的状态。而且我不知道必须在哪里调用这个函数才能在第一个函数之后调用它并使用状态中的数据。

export default class Cases extends Component {
    constructor(props) {
        super(props);
        this.state = {
            cases: [],
            photos: [],
        };

        this.addPhotos = this.addPhotos.bind(this);
        this.getCases = this.getCases.bind(this);
        this.renderCases = this.renderCases.bind(this);
    }

    getCases() {
        axios
            .get('/cases/api')
            .then(response => {
                this.setState({
                    cases: response.data.cases,
                    photos: response.data.photos,
                });
                console.log(this.state.cases);
            })
            .catch((error) => {
                if (error) {
                    console.log(error);
                }
            });
    }

    addPhotos() {
        const newCases = this.state.cases.map(({ photo_id, ...rest }) => {
            const obj = { ...rest };
            this.state.photos.find(data => {
                if (data.id === photo_id) {
                    obj.file = data.file;
                    return true;
                }
            });
            return obj;
        });

        console.log(this.state.cases);

        this.setState({
          'cases' : newCases
        });

    }

    renderCases() {
        this.addPhotos();
    }

    componentWillMount() {
        this.getCases();
    }


    render() {
        return (
            <div>
              {this.renderCases()}
           </div>
        )
    }
}

这就是我现在拥有的

我应该在哪里调用 addPhotos 函数,以便它可以更新状态并仍然使用 getCases 函数中的现有状态数据?

提前致谢!

最佳答案

所以,第一件事是第一位的。生命周期方法 componentWillMount() 很快就会被弃用,并且被认为使用起来不安全。您应该使用 componentDidMount()。

就在 addPhotos 函数中使用更新后的状态而言,您可以向 setState 传递回调函数。一个看似简单的解决方案是将 addPhotos 函数作为回调传递到 getCases 函数中调用的 setState 中。

 getCases() {
        axios
            .get('/cases/api')
            .then(response => {
                this.setState({
                    cases: response.data.cases,
                    photos: response.data.photos,
                }, this.addPhotos);
                console.log(this.state.cases);
            })
            .catch((error) => {
                if (error) {
                    console.log(error);
                }
            });
    }

另一个解决方案是从 componentDidUpdate 调用 addPhotos() 。

希望这有帮助!

编辑:只是 React 文档中的一些额外背景信息。

Think of setState() as a request rather than an immediate command to update the component. For better perceived performance, React may delay it, and then update several components in a single pass. React does not guarantee that the state changes are applied immediately.

setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall. Instead, use componentDidUpdate or a setState callback (setState(updater, callback)), either of which are guaranteed to fire after the update has been applied. If you need to set the state based on the previous state, read about the updater argument below.

关于javascript - 如何调用使用状态(由另一个函数设置)并更新状态的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55964099/

相关文章:

javascript - 在AngularJS中使用ng-repeat迭代数组列表的数组列表

javascript - 可变对象的依赖注入(inject)

reactjs - 笨蛋。如何需要一个react模块?

javascript - 如何在Material ui中保持一致的宽度

javascript - 如何获取函数的返回错误值? ( react native )

javascript toISOString 返回不正确的日期问题

javascript - nodejs回调代码已同步

javascript - 如何从 mongoDB 获取特定日期之间的数据(日期在我们的文档中存储为createdOn)?

javascript - 如何测试返回函数值

reactjs - 类型中缺少不应手动传递给子组件的属性