首页 > 解决方案 > 如果我使用 mapStateToProps,输入属性不会改变

问题描述

我是 Reactjs 的新手。我有角度背景。我面临手动更改字段纬度的问题。我尝试将 onChange 与 handleChange- 一起使用,但它不起作用我做错了什么?

代码

   class Form extends React.Component {
    constructor(props){
        super(props);
    }
    handleChange(value) {
        let coords= {...this.state.coords}
        coords.latitude = value;
        this.setState({coords})

    }


    render() {
        return (<div>
                    <label htmlFor ="latitude">Широта</label>
                    <input id='latitude' type='text'
                           onChange={(event) => this.handleChange(event.target.value)} value={this.props.coords.latitude} />
                    <label htmlFor ="longitude">Долгота</label>
                    <input id='longitude'  onChange={(type) => {
                               this.setState({type});
                    }}  type='text' value={this.props.coords.longitude}  />
                    <input onClick={this.handleClick} type='submit' value='Посмотреть на карте'/>
                </div>
        );
    }
}

function mapStateToProps(state) {
    return {
        coords: state.coords
    }
}


export default connect(mapStateToProps)(Form);

标签: reactjs

解决方案


您正在将mapStateToProps连接器提供的道具与组件的内部混合state

如果您想要更改商店中的纬度,则需要dispatch一个进行更改的事件,然后组件将自动更改其值。

你也需要实施mapDispatchToProps

请参阅官方指南,其中提到了如何正确实施这一点。


推荐阅读