从另一个组件 ReactJS 更新组件状态



我正在为我的应用程序制作登录内容。我只想更新TodoApp.jsx组件中的"用户名"并将其设置为与Login.jsx"用户名"相同的值

有什么建议吗?

TodoApp.jsx

class ToDoApp extends Component {
state = {
username:'',
inputValue: '',
todos: [],
currentPage: 1,
pageCount: 1,
itemsPerPage: 10,
};

此函数创建新项并将其添加到状态中的待办事项:[]

addItem = () => {
let {todos} = this.state
if (this.inpRef.current.value === '') {
return alert('We dont do that here....')
} else {
axios
.post(`http://localhost:8080/add`, {
todo: this.inpRef.current.value,
checked: false,
})
.then((res) => {
this.setState({
todos:[...todos,{todo:res.data.todo,_id:res.data._id,checked:false}]
})
})
.catch((err) => {
console.log("err", err);
});
this.setPageCount()
}
this.inpRef.current.value = ''
console.log('--------this.state.todos', this.state.todos);
}

这是Login.jsx代码:

class Login extends Component {
state = {
username:'',
password:'',
}

这是一个处理登录的函数。

handleLogIn = () => {
const { username, password } = this.state
if (password.length === 0 || username.length === 0 ) {
alert('Incorrect Login!')
} else {
axios
.post(`http://localhost:8080/logIn`, {
username: username,
password: password,
})
.then((res) => {
this.props.history.push("/todoapp");
console.log('res',res)
})
.catch((err) => {
console.log("err", err);
});
}
}

你可以使用 React 的props属性.js来实现这一点。 如果我们假设您在ToDoApp中调用了Login 组件(这使得ToDoApp成为父组件,Login成为子组件(;然后,您可以做的是定义一个设置子组件的用户名状态的方法。

例如:

登录组件:设置用户名状态后调用父组件的handle_username函数。

this.setState({username: (username input)})    
this.props.handle_username(this.state.username)

ToDoApp 组件:定义函数handle_username并将其作为道具传递给登录组件。

handle_username = (username) => {
this.setState({username: username})
}

结束传递它作为道具:

<Login handle_username={this.handle_username}/>
  1. 您可以使用 Redux 来实现此目的。
  2. 在这两个组件之间传递道具。
  3. 调用 API 以更新数据并在另一个页面上获取 API。
  4. 使用浏览器本地存储来存储输入数据。