如何使redux实现类似于双向绑定的功能?

查看:159
本文介绍了如何使redux实现类似于双向绑定的功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

最近在学习redux入门,找了一些教程之后想实现类似一个双向绑定的小功能。代码如下:
问题就出在reducer部分 我应该如何取到组件中的定义的事件中的值??

import React from 'react';
import ReactDOM from 'react-dom';
import {
    createStore,
    bindActionCreators
} from 'redux';
import {
    Provider,
    connect
} from 'react-redux';


//action
function changeText() {
    return {
        type: "CHANGE_TEXT"
    }
}

//reducers
const initalState = {
    text: 'hello world'
}

function myApp(state = initalState, action) {
    switch (action.type) {
        case 'CHANGE_TEXT':
            return {
                text: state.text = 
                // 问题就是在这里如何取到e.target.value!!!
            }
        default:
            return {
                text: 'hello world'
            }
    }
}

//store
let store = createStore(myApp);

class Input extends React.Component {
    constructor(props) {
        super(props);
        this.handleChange = this.handleChange.bind(this);
    }

    handleChange(e) {
        this.props.actions.changeText(e.target.value);
    }
    render() {
        return (
            <div>
                  <input type="text"  value={this.props.text} onChange={this.handleChange}/>
                  <p>{this.props.text}</p>
              </div>
        )
    }
}

class App extends React.Component{

    constructor(props) {
        super(props);
    }

    render() {
        const {actions, text} = this.props;
        return ( 
            <div>
                <Input actions={actions} text={text} />
            </div>
        );
    }
}

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

function mapDispatchToProps(dispatch) {
    return {
        actions: bindActionCreators({
            changeText: changeText
        }, dispatch)
    }
}

App = connect(mapStateToProps, mapDispatchToProps)(App)

ReactDOM.render(
    <Provider store={store}>
        <App />
    </Provider>,
    document.getElementById('root')
)

解决方案

不是取e.target.value的值,而是由你的action传过来的。

//action

function changeText(text) {
    return {
        type: "CHANGE_TEXT",
        text
    }
}

用action.text来取即可。当然你代码中其他还有几处是需要修改的。看看todo这个DEMO就知道了。

这篇关于如何使redux实现类似于双向绑定的功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆