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

时间:2020-06-16 08:09:07

标签: reactjs react-native

我正在为我的应用程序创建“登录资料”。我要做的就是更新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);
                });
        }
    }

2 个答案:

答案 0 :(得分:1)

  1. 您可以使用Redux来实现这一目标。
  2. 在这两个组件之间传递道具。
  3. 调用API来更新数据并在另一页上获取API。
  4. 使用浏览器本地存储来存储输入数据。

答案 1 :(得分:1)

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

例如:

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

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

ToDoApp组件:定义功能 handle_username 并将其作为道具传递给 Login 组件。

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

以道具结束传递:

<Login handle_username={this.handle_username}/>