【问题标题】:React componentDidMount confusionReact componentDidMount 混淆
【发布时间】:2020-04-07 05:00:14
【问题描述】:

我对某些行为感到困惑,想知道是否有人可以提供帮助。我有一个 React 组件,它根据通过 props 传入的过滤器来获取电影数据。使用 console.log 我可以看到我的 componentDidMount() 只被调用一次,但每次组件由于接收不同的道具而重新渲染时,只在 componentDidMount() 中设置的状态变量会发生变化。我的代码很长,所以我不想全部发布,但如果需要我可以发布。引起我困惑的sn-p如下:

class MoviesList extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
                        filterList : [], filter: {}
        };
    }
    async componentDidMount() {
        console.log("shouldOnlyCallOnce");
        if( this.props.filter.on) {
            if (this.props.filter.type == "title"){
                try {
                    const url = "mycustomapi.com/api/"+this.props.filter.title;
                    const response = await fetch(url);
                    const jsonData = await response.json();
                    jsonData.sort((a, b) => a.title.localeCompare(b.title));
                    console.log("??");
                    this.setState({filterList: jsonData, filter: this.props.filter});
                }
                catch (error) {
                    console.error(error);
                }
            }

尽管 state.filter 仅在整个组件中设置,但每次重新加载我的组件时它都会更改。有谁知道如果没有多次控制台记录会发生这种情况?

【问题讨论】:

  • 除了这个问题,我的 componentDidUpdate(prevProps){} prevProps 总是和我现在的 props 一样。

标签: javascript reactjs


【解决方案1】:

在我看来,唯一的解释是您正在修改此组件之外的过滤器的内容。

考虑一下:

let filterA = { title: 'foo' }

let filterB = filterA
console.log(filterB.title) // Shows 'foo'

filterA.title = 'bar'
console.log(filterB.title) // Shows 'bar'

尽管我们在这里从未直接修改过 filterB,但值发生了变化。这是因为 filterA 和 filterB 引用的是同一个对象,所以它们当然都会改变。

如果您在您的情况下将过滤器作为道具传递,然后在父级内部修改过滤器,则过滤器也会在子级中更改。

附带说明:您所做的称为从道具派生状态,这意味着您正在使用道具来设置状态。这几乎从来都不是好的做法。 https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html

【讨论】:

  • 谢谢,这一定是发生的事情,我知道我只是在尝试调试时将状态设置为道具。我遇到的真正问题是我的 this.props 始终与 componentDidUpdate 中的 prevProps 相同,但我会尝试解决这个问题,谢谢。
  • 哇,你的回答救了我,我只需要在父组件中创建一个新的 props 对象,而不是仅仅修改它来解决我的其他问题。再次感谢
【解决方案2】:

ComponentDidMount 将在组件开始渲染时触发。在 props 或 state 改变后,ComponentDidUpdate 将触发。请查看链接:react life cycle example

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-12
    • 2020-11-29
    • 2017-03-14
    • 2018-02-25
    • 2020-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多