【问题标题】:Using context in React Native to render TextInput values在 React Native 中使用上下文来渲染 TextInput 值
【发布时间】:2021-06-29 09:11:09
【问题描述】:

尝试创建具有全局可访问值数组的功能,这些值可由用户输入,然后在不同组件中输出和/或编辑。

我已经能够在一个屏幕中创建一个对象数组并使其输出正常,但我需要在另一个屏幕中显示相同的数组才能选择选项。

我不断收到此错误:

Error: Objects are not valid as a React child (found: object with keys {dispatchConfig, _targetInst, _dispatchListeners, _dispatchInstances, type, target, currentTarget, eventPhase, bubbles, cancelable, timeStamp, defaultPrevented, isTrusted, touchHistory, nativeEvent, isDefaultPrevented, isPropagationStopped}). If you meant to render a collection of children, use an array instead.

据我所知,不幸的是,很多搜索结果最终都不适用​​于我的特定问题。

WeightContext.js:


const WeightContext = createContext();

const WeightProvider = (props) => {
    const [weights, setWeights]= useState([]);
    return (
        <WeightContext.Provider value={[weights, setWeights]}>
            {props.children}
        </WeightContext.Provider>
    );
}
export { WeightContext, WeightProvider };

App.js:

import React from 'react';
import { View, Text } from 'react-native';
import {styles} from './styles/styles';
import { WeightProvider } from './contexts/WeightContext';
import Header from './components/Header';
import AddWeight from './components/AddWeight';
import WeightList from './components/WeightList';

const App = () => {

    return (
      <WeightProvider>
        <View style={styles.container}>
          <Text style={styles.headings}>App Component</Text>
            <Header />
            <AddWeight />
            <WeightList />  
        </View>
      </WeightProvider>
    );
}

export default App;

Header.js

import React, { useContext } from 'react';
import { View, Text } from 'react-native';
import { WeightContext } from '../contexts/WeightContext';
import { styles } from '../styles/styles';

const Header = () => {
    const [weights, setWeights] = useContext(WeightContext);

    return (
        <View style={styles.screen}>
            <Text style={styles.subHeading}>Weight Amounts List</Text>
            <Text style={styles.paragraph}>Total entries in weights: {weights.length}</Text>
        </View>
    );
}

export default Header;

WeightList.js:

import { View, Text } from 'react-native';
import Weight from './Weight';
import { WeightContext } from '../contexts/WeightContext';
import { styles } from '../styles/styles';

const WeightList = () => {
    const [weights, setWeights] = useContext(WeightContext)

    return (
        <View>
            <Text style={styles.subHeading}>Weight List</Text>
            {weights.map((item) => {
                return (
                    <Weight amount={item.amount} key={item.id}/>
                );
            })}
            
        </View>
    );
}

export default WeightList;

AddWeight.js

import React, { useContext, useState } from 'react';

import { View, Text, TextInput, Button } from 'react-native';
import { WeightContext } from '../contexts/WeightContext';
import { styles } from '../styles/styles';

const AddWeight = (onAddAmount) => {
    const [weights, setWeights] = useContext(WeightContext)

//// variables
    const [amount, setAmount] = useState('');

/// functions    
    const updateAmount = (valueEntered) => {
        setAmount(valueEntered);
    };

    const addAmountHandler = (amount) => {
        setWeights((prevWeights) => {
            return [...prevWeights, {id: Math.random().toString(), amount: amount}];
        });
    }

    return (
        <View style={styles.screen}>
            <Text>Add Weight</Text>
            <TextInput 
                placeholder="Add new Amount"
                maxLength={2}
                keyboardType={'numeric'}
                value={amount}
                onChangeText={updateAmount}
            />
            <Button title="ADD NEW WEIGHT" onPress={addAmountHandler}/>
        </View>
    );
}

export default AddWeight;

Weight.js

import React from 'react';
import { View, Text } from 'react-native';
import { styles } from '../styles/styles';

const Weight= ({amount}) => {

    return (
        <View style={styles.screen}>
            <Text style={styles.paragraph}>{amount}</Text>
        </View>
    );
}

export default Weight;

提前致谢!

【问题讨论】:

    标签: javascript react-native state-management react-context


    【解决方案1】:

    替换这个: const addAmountHandler = (amount) =&gt; {...}

    有了这个: const addAmountHandler = () =&gt; {...}

    【讨论】:

    • 成功了,感谢您的帮助!您能否详细说明为什么这是解决方案?
    • @MaceyMace 当按钮被点击时,addAmountHandler 在没有参数的情况下被调用。这会导致 amount 参数未定义。
    【解决方案2】:

    这可能有效:

    尝试将这样的值放入提供程序

    value={{weights, setWeights}}
    

    要这样使用它们:

    const {weights, setWeights} = useContext(WeightContext);
    

    【讨论】:

    • 我现在得到这个:``` TypeError: undefined is not an object (evalating 'weights.map') ```
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    • 1970-01-01
    • 2019-10-28
    • 2023-01-04
    • 2019-08-14
    • 2015-06-02
    相关资源
    最近更新 更多