如何使用redux和react native在两个屏幕之间传递数据



我想用redux将dropdownSelect的值从View1传递到View2

View1 * * * *

function View1(props) {
const [val, setVal] = React.useState(null);
function handleSelect(e) {
setVal(e);
if (e !== null) {
props.GetDropDownValue(e);
}
console.log(data[e]);
console.log(e);
}
const data = ["op1", "op2", "op3", "op4", "op5", "op6"];
return (
<Text style={styles.text}>View 1</Text>
<ModalDropdown
options={data}
defaultValue="default"
onSelect={handleSelect}
/>
);
}
const mapDispatchToProps = {
GetDropDownValue,
};
export default connect(null, mapDispatchToProps)(View1);

View2 * * *

function View2(props) {
return (
<Text style={{ fontSize: 30, color: "white" }}>
value is :{???}
</Text>
);
}
function mapStateToProps(state) {
return {
vals: state.vals,
};
}
export default connect(mapStateToProps)(View2);

这是我的动作文件

action.js * * *

export function GetDropDownValue(DPValue) {
return {
type: "GET_VALUE",
DPValue: DPValue,
};
}

ReduxApp.js * * *

const initialState = {
dropdownValue: 0,
};
function dropdown(state = initialState.dropdownValue, action) {
switch (action.type) {
case "GET_VALUE":
return action.DPValue
default:
return state;
}
}
const store = createStore(dropdown);
export default class ReduxApp extends Component {
render() {
return (
<>
<Provider store={store}>
<View style={styles.container}>
<View1 />
<View2 />
</View>
</Provider>
</>
);
}
}

这是我的完整代码,在View2中,我不知道如何调用从下拉菜单中选择的值,也许在我的代码中还有其他错误,请帮助我解决这个问题:)

View 1-

function View1() {
const [val, setVal] = React.useState(null);
const dispatch=useDispatch();//import {useDispatch} from "react-redux"
function handleSelect(e) {
setVal(e);
if (e !== null) {
dispatch(GetDropDownValue(e));
}
console.log(data[e]);
console.log(e);
}
const data = ["op1", "op2", "op3", "op4", "op5", "op6"];
return (
<Text style={styles.text}>View 1</Text>
<ModalDropdown
options={data}
defaultValue="default"
onSelect={handleSelect}
/>
);
}
export default View1;

视图2 -

function View2() {
const dropdownValue=useSelector(state=>state.dropdownValue);
//import {useSelector} from "react-redux"
return (
<Text style={{ fontSize: 30, color: "white" }}>
value is :{dropdownValue}
</Text>
);
}

export default View2;

ReduxApp.js * * *

const initialState = {
dropdownValue: 0,
};
function dropdown(state = initialState.dropdownValue, action) {
switch (action.type) {
case "GET_VALUE":
return {
...state,
dropdownValue:action.DPValue
}
default:
return state;
}
}
const store = createStore(dropdown);
export default class ReduxApp extends Component {
render() {
return (
<>
<Provider store={store}>
<View style={styles.container}>
<View1 />
<View2 />
</View>
</Provider>
</>
);
}
}

最新更新