ReactJS 上下文:通过上下文传递数组
ReactJS Context: Passing array through context
我目前有一个项目,我需要将数组传递给搜索栏的另一个组件。我正在使用 React 的上下文。
我已经尝试传递我的数据,但我似乎在我的控制台中得到了一个未定义的值。
Context.js
中的代码
Export const SearchContext = createContext();
这是MainPage.js中的代码:
const data = [json_1, json_2];
const array = data.map(values => {
const search = _.flattenDeep(values);
values.search = search;
return values;
})
<SearchContext.Provider value={array} />
在我的 Searchbar.js
const options = useContext(SearchContext);
console.log(options);
<AutoComplete
className="searchbar"
placeholder="Search..."
dataSource = {options}
onfilterOption={(inputValue, option) =>
option.props.children.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1
}
/>
在 console.log 中我得到一个未定义的值。此数据也应该能够填充我的搜索栏。
请看这个要点:https://gist.github.com/nimahkh/9c008aaf2fd2d1cc83cd98c61e54979a
你必须用 Provider 包装你的组件,并且在被包装的组件内部,你可以访问 value ,不可能获取 value ,开箱即用
我目前有一个项目,我需要将数组传递给搜索栏的另一个组件。我正在使用 React 的上下文。
我已经尝试传递我的数据,但我似乎在我的控制台中得到了一个未定义的值。
Context.js
中的代码Export const SearchContext = createContext();
这是MainPage.js中的代码:
const data = [json_1, json_2];
const array = data.map(values => {
const search = _.flattenDeep(values);
values.search = search;
return values;
})
<SearchContext.Provider value={array} />
在我的 Searchbar.js
const options = useContext(SearchContext);
console.log(options);
<AutoComplete
className="searchbar"
placeholder="Search..."
dataSource = {options}
onfilterOption={(inputValue, option) =>
option.props.children.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1
}
/>
在 console.log 中我得到一个未定义的值。此数据也应该能够填充我的搜索栏。
请看这个要点:https://gist.github.com/nimahkh/9c008aaf2fd2d1cc83cd98c61e54979a
你必须用 Provider 包装你的组件,并且在被包装的组件内部,你可以访问 value ,不可能获取 value ,开箱即用