1

react 的官方文档(https://reactjs.org/docs/react-component.html)说 props 的更新会导致孩子被更新,但在我的代码中并没有发生。我错过了什么吗?

我创建了一个父组件 (Y) 和一个子组件 (X)。父母将 currentTime 作为道具传递给孩子。即使在 3 秒后父项中的 props 发生变化(由于 setTimeout),子项中 h2 标记中的值也不会改变。

我在 react 的官方页面(https://reactjs.org/docs/react-component.html)上发现“更新可能是由 props 或 state 的更改引起的。” (我在下面的官方网站上附上了屏幕截图以及文本)此外,我发现“这些方法在重新渲染组件时被调用:”

componentWillReceiveProps()
shouldComponentUpdate()
componentWillUpdate()
render()
componentDidUpdate()

但在我的情况下,道具的变化不会导致孩子中 h2 标签中的值发生变化。官方文档说 props 的更新会导致 child 被更新,但在我的代码中并没有发生。我错过了什么吗?

我在这里粘贴了我的代码以供参考。

const Y = () => {

    let currentTime="09:00";
    setTimeout(()=> {
            currentTime = "10:00:"
        }, 3000);

    return (
        <X time={currentTime}/>
    );
};


class X extends Component {
    time = "11:00";

    render = () => {
        return (
            <h2>{this.props.time}</h2>
        );
    };
}

截图: https ://prnt.sc/i8kvaw

更新:Shubham Khatri 的评论“只有当父母重新渲染时,孩子的道具才会改变”,真的帮助我理解了。:)

4

2 回答 2

1

即使组件 Y 中的 props 值 currentTime 发生了变化,它也不会再次重新渲染,因此子 props 不会更新。如果将 currentTime 存储在父状态中,然后使用 setState 设置 Y 组件的状态,它会触发组件的重新渲染,因此子组件 X 会接收到新的道具

class Y extends Component {

    state = {
        currentTime: "9:00 AM"
    };

    componentDidMount() {
        setTimeout(() => {
            this.setState({currentTime: "10:00"}
        }, 3000);
    }

    render() {
        return (
             <X time={currentTime}/>
        );
    }

};


class X extends Component {

    render = () => {
        return (
            <h2>{this.props.time}</h2>
        );
    };
}
于 2018-02-01T10:27:09.817 回答
0

父组件中的 setTimeout 只是改变 currentTime 变量的值。父函数中的渲染函数不会重新渲染,以便更新子函数。

您需要在父组件中为 currentTime 设置状态。

this.state = {
  currentTime:"09:00"
}

现在你可以做

componentDidMount() {
    setTimeout(() => {
        this.setState({ currentTime: "10:00" }
    }, 3000);
}

这将使父级重新渲染,而子级将使用新道具进行更新。

于 2018-02-01T10:28:54.063 回答