#javascript #reactjs #react-native #navigation
Вопрос:
Я пытаюсь передать простую переменную на новый экран и точно следовал этому руководству: https://reactnavigation.org/docs/params/. Я подтвердил, что переменная, которую я передаю, существует и имеет правильное значение, но на новом экране, когда я пытаюсь распечатать или использовать ее, она полностью пуста. Кажется, его не существует. Что я упускаю?
Исходный (отправляющий) экран (перейдите к кнопке внизу, которая отправляет навигацию.перейдите и укажите количество игроков):
import * as React from 'react';
import { StyleSheet, View, Text, Button } from 'react-native';
import DropDownPicker from 'react-native-dropdown-picker';
import {useState} from "react";
import { useCallback } from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
export default function SetupScreen( {navigation} ){
const [playersOpen, setPlayersOpen] = useState(false);
const [playersValue, setPlayersValue] = useState(null);
const [playersItems, setPlayersItems] = useState([
{label: '2-Max', value: '2'},
{label: '6-Max', value: '6'},
{label: '9-Max', value: '9'}
]);
const onPlayersOpen = useCallback(() => {
setCityOpen(false);
}, []);
const [blindsOpen, setBlindsOpen] = useState(false);
const [blindsValue, setBlindsValue] = useState(null);
const [blindsItems, setBlindsItems] = useState([
{label: '$0.01 / $0.02', value: '0.02'},
{label: '$0.05 / $0.10', value: '0.10'},
{label: '$0.10 / $0.20', value: '0.20'},
{label: '$0.25 / $0.50', value: '0.50'},
{label: '$0.50 / $1.00', value: '1'},
{label: '$1 / $2', value: '2'},
{label: '$2 / $5', value: '5'},
{label: '$5 / $10', value: '10'}
]);
const onBlindsOpen = useCallback(() => {
setCountryOpen(false);
}, []);
return (
<View style={styles.container}>
<View>
<Text>Select Table Size</Text>
<DropDownPicker
zIndex = {3000}
zIndexInverse = {1000}
open={playersOpen}
value={playersValue}
items={playersItems}
setOpen={setPlayersOpen}
setValue={setPlayersValue}
setItems={setPlayersItems}
/>
<Text>Select stakes</Text>
<DropDownPicker
zIndex = {2000}
zIndexInverse = {2000}
open={blindsOpen}
value={blindsValue}
items={blindsItems}
setOpen={setBlindsOpen}
setValue={setBlindsValue}
setItems={setBlindsItems}
/>
</View>
<View style={styles.buttonSection}>
<Text>Players: {JSON.stringify(playersValue)}</Text>
<Text>Blinds: {JSON.stringify(blindsValue)}</Text>
<Button
zIndex = {1000}
title={"Begin Session"}
onPress={() => {
navigation.navigate('SessionScreen', {
PV: playersValue,
});
}}
/>
<Button title="Go to Home" onPress={() => navigation.navigate('Home')} />
<Button title="Go back" onPress={() => navigation.goBack()} />
</View>
</View>
);
};
const styles = StyleSheet.create ({
container: {
flex: 1,
flexDirection: 'column',
justifyContent: 'space-between',
alignItems: 'center',
backgroundColor: 'green',
},
buttonSection: {
height: 300
},
})
Экран назначения (Рассматриваемая команда находится справа вверху)
import * as React from 'react';
import {Component} from 'react'
import {useState} from "react";
import { StyleSheet, View, Text, Button } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
export default function SessionScreen ( {route, navigation} ) {
const {tableSize, setTableSize} = useState(route.params)
const [players, setPlayers] = useState(tableSize)
const [bigBlind, setBigBlind] = useState(2)
const [progress, setProgress] = useState("Initialization")
const [activePlayer, setActivePlayer] = useState(0)
const [handRecord, setHandRecord] = useState("")
const nextStage = () => {
setProgress("Preflop")
}
var makeArray = (numP) => {
var array = [
<Button title="Hero" key={0} />,
<Button title="Villain 1" key={1}/>,
<Button title="Villain 2" key={2}/>,
<Button title="Villain 3" key={3}/>,
]
if (numP >= 6) {
array.push([<Button title="Villain 4" key={4}/>,
<Button title="Villain 5" key={5}/>])
}
if (numP === 9) {
array.push([<Button title="Villain 6" key={6}/>,
<Button title="Villain 7" key={7}/>, <Button title="Villain 8" key={8}/>])
}
return array
}
return (
<View style = {styles.container}>
<View>
<Text>
Players: {JSON.stringify(tableSize)}</Text>
{makeArray(players)}
</View>
<View>
<Text>Session Screen</Text>
{/* {progress === "Initialization" amp;amp;
<Button title="nextRound" onPress={() => nextStage()}/>
}
{progress === "Preflop" amp;amp;
//<Button title="add player" onPress={() => this.setState({players: 6})}/>
<Text>Got to second if</Text>
} */}
<Text>Got past second if</Text>
<Button
title="Go to History Screen"
onPress={() => navigation.push('HistoryScreen')}
/>
<Button title="Go to Home" onPress={() => navigation.navigate('Home')} />
<Button title="Go back" onPress={() => navigation.goBack()} />
</View>
<View>
<Text>{progress}</Text>
</View>
</View>
);
}
const styles = StyleSheet.create ({
container: {
flex: 1,
flexDirection: 'column',
justifyContent: 'space-between',
alignItems: 'center',
backgroundColor: 'green',
},
buttonSection: {
height: 300
},
})
Комментарии:
1. Я не уверен, что вам нужно состояние пользователя. Можете ли вы попробовать это вместо этого: const {tableSize, setTableSize} = параметры маршрута
2. Эй, к сожалению, это ничего не изменило — переменная все еще не взаимодействует с моим кодом.
Ответ №1:
Я думаю, тебе это не нужно tableSize
? Просто получите PV
ценность от route.params
:
const [players, setPlayers] = useState(route.params.PV)