使用connect 将组件连接到mapStateToProps 的状态。
Redux 声明您的“映射到道具”将通过您连接的组件道具可用
要更新 redux 状态,请使用同样通过第二个 arg 传递给组件 props 的操作创建器到 connect
您现在可以将Settings 转换为函数式组件:
import * as React from 'react';
import {connect} from 'react-redux';
import { Text, View } from 'react-native';
export default Settings = (props) => {
const { value } = props;
return (
<View>
<Text>
This is the settings screen. I want to render a value from the state here: { value }
</Text>
</View>
);
}
const mapStateToProps(state){
return {
value: state.value
}
}
export default connect(mapStateToProps)(Settings)
你需要一个减速器:
export default const reducer = (state = '', action) => {
switch (action.type) {
case 'UPDATE_VALUE' :
return action.payload
case 'REMOVE_VALUE' :
return ''
default:
return state
}
}
您还需要一些动作创建者:
export const updateValue = (newValue) = {
return {type: 'UPDATE_VALUE', payload:newValue}
}
export const removeValue = (newValue) = {
return {type: 'REMOVE_VALUE'}
}
然后您可以使用这些动作创建者来更新状态:
import React from "react";
import { connect } from "react-redux";
import { Button } from 'react-native-paper';
import { updateValue , removeValue } from './actions'
const SomeComponent = props => {
return(
<div>
<Button onPress={()=>props.updateValue(‘newValue’)}>Update</button>
<Button onPress={()=>props.removeValue()}>Remove</button>
</div>
)
}
//set mapStateToProps arg to null if you do not need state
export default connect(null , {updateValue , removeValue})(SomeComponent);