gpt4 book ai didi

javascript - React props 和 states-值不更新

转载 作者:行者123 更新时间:2023-12-02 22:03:48 25 4
gpt4 key购买 nike

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

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;

最佳答案

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

    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" }
]
});

关于javascript - React props 和 states-值不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59787356/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com