反应道具和状态-价值不会更新

时间:2020-01-17 12:28:19

标签: javascript html reactjs react-props

这是一个使用props和state的简单反应示例。当用户在给定的输入插槽中键入名称时,显示的名称应在输出部分中相应地更新。但是该值不会更新。您可以在代码中找到错误吗?

App.js

import "./App.css";
import UserInput from "./Person/userInput";
import UserOutput from "./Person/userOutput";

class App extends Component {
  state = {
    userName: [
      { name: "Max", age: 28, proff: "doctor" },
      { name: "Tom", age: 20, proff: "engg" },
      { name: "Dev", age: 23, proff: "writter" }
    ]
  };

  eHandler = event => {
    this.setState = ({
      userName: [
        { name: event.target.value, age: 28, proff: "doctor" },
        { name: event.target.value, age: 20, proff: "engg" },
        { name: event.target.value, age: 23, proff: "writter" }
      ]
    });
  };

  render() {
    return (
      <div className="App">
        <div className="card">
          <UserOutput
            name={this.state.userName[0].name}
            age={this.state.userName[0].age}
            proff={this.state.userName[0].proff} 
          />
          <UserInput changed={this.eHandler} />
        </div>
        <div className="card">
          <UserOutput
            name={this.state.userName[1].name}
            age={this.state.userName[1].age}
            proff={this.state.userName[1].proff}
          />
        </div>
        <div className="card">
          <UserOutput
            name={this.state.userName[2].name}
            age={this.state.userName[2].age}
            proff={this.state.userName[2].proff}
          />
          <UserInput changed={this.eHandler} />
        </div>
      </div>
    );
  }
}

export default App;

组件- userInput.js


const userInput = props => {
  return (
    <div>
      <input type="text" onChange={props.changed}></input>
    </div>
  );
};

export default userInput;

组件- userOutput.js

import React from "react";

const userOutput = props => {
  return (
    <div>
      <p>
        {props.name} of age {props.age} is a {props.proff}
      </p>
    </div>
  );
};
export default userOutput;

1 个答案:

答案 0 :(得分:1)

您在处理程序中的状态更新是错误的。应该是以下内容。

    this.setState({
      userName: [
        { name: event.target.value, age: 28, proff: "doctor" },
        { name: event.target.value, age: 20, proff: "engg" },
        { name: event.target.value, age: 23, proff: "writter" }
      ]
    });