注入actionCreator与mapDispatchToProps有什么好处?

时间:2017-03-20 04:19:18

标签: javascript reactjs redux react-redux

我正在浏览connect docs并试图理解这个例子:

  

注入待办事项和所有动作创建者

import * as actionCreators from './actionCreators'

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

export default connect(mapStateToProps, actionCreators)(TodoApp)

为什么这里不需要mapDispatchToPropsdispatch在哪里?

我理解行动,dispatchmapDispatchToProps,但我对动作创作者和上述语法有点模糊。

1 个答案:

答案 0 :(得分:1)

您可以传递ObjectFunction

如果传递了一个对象,则其中的每个函数都被假定为Redux动作创建者。 Connect会将dispatch绑定到import * as actionCreators from './actionCreators'; connect(mapStateToProps, actionCreators)(TodoApp)

this.props.someActionCreator();

然后在组件

bindActionCreators()

如果传递了一个函数,它将被分配给它。由您来返回一个以某种方式使用dispatch以您自己的方式绑定动作创建者的对象。您可以使用Redux的ownProps助手。 如果将mapDispatchToProps指定为第二个参数,则其值将是传递给组件的props,并且只要组件接收到新的道具,就会重新调用function mapDispatchToProps(dispatch) { return { actions: bindActionCreators(actionCreators, dispatch) } }

this.props.dispatch(someActionCreator());

如果省略,默认实现只是将调度注入组件的道具。

然后在组件中:

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements SensorEventListener{



    private SensorManager mSensorManager;
    private Sensor mProximity;
    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
// Get an instance of the sensor service, and use that to get an instance of
        // a particular sensor.
        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        mProximity = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
        mSensorManager.registerListener(this, mProximity, SensorManager.SENSOR_DELAY_NORMAL);
        textView = (TextView) findViewById(R.id.newtext);

    }


    public final void onAccuracyChanged(Sensor sensor, int accuracy) {
        // Do something here if sensor accuracy changes.
    }


    public final void onSensorChanged(SensorEvent event) {
        float distance = event.values[0];
        textView.setText(""+event.values[0]);
        if (distance<3){
            textView.setText("near"+distance);
        }
        // Do something with this sensor data.
    }

    @Override
    protected void onResume() {
        // Register a listener for the sensor.
        super.onResume();
        mSensorManager.registerListener(this, mProximity, SensorManager.SENSOR_DELAY_NORMAL);
    }

    @Override
    protected void onPause() {
        // Be sure to unregister the sensor when the activity pauses.
        super.onPause();
        mSensorManager.unregisterListener(this);
    }
}

source react-redux DOCS

因此,将actionCreators对象注入函数的好处是将actionCrators传递给组件更方便,更简洁的形式