【问题标题】:Updating a single item in React context state在 React 上下文状态中更新单个项目
【发布时间】:2021-01-08 17:45:44
【问题描述】:

所以我有以下格式的上下文:

class UserProvider extends Component {
    constructor(props) {
        super(props)

        this.initialize = (details) => {
            this.setState(state => {
                //Setting each item individually here
                //e.g state.a = details.a
            })
        }

        this.editA = () => {
            this.setState(state => {
                //change A here
            })
        }

        this.editB = () => {
            this.setState(state => {
                //Change B here
            })
        }

        this.state = {
            a: null,
            b: null,
            editA: this.editA,
            editB: this.editB
        }
    }

    render() {
        return (
            <User.Provider value={this.state}>
                {this.props.children}
            </User.Provider>
        )
    }
}

所以对于每个状态,我都有一个单独的函数来更新它。如果我只想更新一个状态,我应该怎么做?

【问题讨论】:

  • 只更新该字段,不为其他人做任何事情.. this.setState({a:'"value"})
  • @EugenSunic 当我想通过消费者访问每个字段时,这是否仍然需要单独的函数
  • 你的意思是你只想要一个函数来更新一个字段,而不是n个字段的n个函数?

标签: javascript node.js reactjs state react-context


【解决方案1】:

考虑实现一个通用函数,以便您可以控制您的键和相应的值。

const changeField = (key, value) => this.setState({ [key]: value});

函数调用

changeField('a','value_a')
changeField('b','value_b')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-02
    • 1970-01-01
    • 2021-07-20
    • 1970-01-01
    • 2021-11-23
    • 1970-01-01
    • 1970-01-01
    • 2021-12-24
    相关资源
    最近更新 更多