代码之家  ›  专栏  ›  技术社区  ›  bula

在道具更新时,react不会重新渲染

  •  0
  • bula  · 技术社区  · 8 年前

    render 方法 FormEl

    return <div>
                <button type="button" onClick={this.clicked}>click to add 1 input</button>
                <Inputs count={this.state.childcount}/>
            </div>
    

    在里面 clicked childcount 由1使用 setState

    Inputs

    class Inputs extends React.Component {
        constructor(props) {
            super(props);
            console.log("Input constructor is running.");
            this.state = {value: '', p: "p", count: props.count};
        }
    
        render() {
            let c = [];
            for (let i = 0; i < this.state.count; i++) {
                c.push(
                    <div key={"id-" + (i * 10)}>
                        <input type="text" defaultValue={this.state.value}/>
                        <p> {this.state.p}</p>
                    </div>);
            }
            return <div>
                {c}
            </div>;
        }
    }
    

    但是,当我更新 在里面 点击 ,我看得出来 福尔梅尔 count <Inputs.. 相应增加。但它没有召唤 constructor 输入 除了第一次(页面加载)时间。

    3 回复  |  直到 8 年前
        1
  •  1
  •   Amruth    8 年前

    直接使用这个。道具。计数相反。

    for (let i = 0; i < this.props.count; i++) {
    
        2
  •  0
  •   vicke4 Josh    8 年前

    Inputs 组件在挂载后只会被调用一次。再也不会叫了。所以,你能做的就是 componentDidUpdate 输入 元件和设置状态 count 道具和你现在的状态不同。

    或者,你可以直接使用 this.props.count 在 for 根据建议 @lsa4299

        3
  •  0
  •   Carlos Ruana    8 年前

    构造函数只能被调用一次,所以您只能在那里设置初始状态。

    事实上,由于您没有从Inputs类修改状态,因此根本不需要任何状态。可以在渲染方法的顶部声明const value=“”;const p=“p”。就用它吧这个。道具。计数而不是此.state.count

    在这种情况下,可以删除构造函数。

    如果您稍后修改组件的行为,并且需要根据新的props(不是当前情况)设置状态,您可能需要检查getDerivedStateFromProps方法。